Part Number Hot Search : 
A3988 L2101 08783 3DD1300 KA3525A 80000 LM190 2SK1519
Product Description
Full Text Search
 

To Download ATTINY84V-10MUR Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  features ? high performance, low power atmel ? avr ? 8-bit microcontroller ? advanced risc architecture ? 135 powerful instructions ? most single clock cycle execution ? 32 8 general purpose working registers ? fully static operation ? up to 16 mips throughput at 16mhz ? on-chip 2-cycle multiplier ? high endurance non-volatile memory segments ? 64k/128k/256kbytes of in-system self-programmable flash ? 4kbytes eeprom ? 8kbytes internal sram ? write/erase cycles:10,000 flash/100,000 eeprom ? data retention: 20 years at 85 c/ 100 years at 25 c ? optional boot code section with independent lock bits ? in-system programming by on-chip boot program ? true read-while-write operation ? programming lock for software security ? endurance: up to 64kbytes optional external memory space ? atmel ? qtouch ? library support ? capacitive touch buttons, sliders and wheels ? qtouch and qmatrix? acquisition ? up to 64 sense channels ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities according to the jtag standard ? extensive on-chip debug support ? programming of flash, eeprom, fuses, and lock bits through the jtag interface ? peripheral features ? two 8-bit timer/counters with separate prescaler and compare mode ? four 16-bit timer/counter with separate prescaler, compare- and capture mode ? real time counter with separate oscillator ? four 8-bit pwm channels ? six/twelve pwm channels with programmable resolution from 2 to 16 bits (atmega1281/2561, atmega640/1280/2560) ? output compare modulator ? 8/16-channel, 10-bit adc (atmega1281/2561, atmega640/1280/2560) ? two/four programmable serial usart (atmega1281/2561, atmega640/1280/2560) ? master/slave spi serial interface ? byte oriented 2-wire serial interface ? programmable watchdog timer with separate on-chip oscillator ? on-chip analog comparator ? interrupt and wake-up on pin change ? special microcontroller features ? power-on reset and programmable brown-out detection ? internal calibrated oscillator ? external and internal interrupt sources ? six sleep modes: idle, adc noise reduction, power-save, power-down, standby, and extended standby ? i/o and packages ? 54/86 programmable i/o lines (atmega1281/2561, atmega640/1280/2560) ? 64-pad qfn/mlf, 64-lead tqfp (atmega1281/2561) ? 100-lead tqfp, 100-ball cbga (atmega640/1280/2560) ? rohs/fully green ? temperature range: ?-40 c to 85 c industrial ? ultra-low power consumption ? active mode: 1mhz, 1.8v: 500a ? power-down mode: 0.1a at 1.8v ? speed grade: ? atmega640v/atmega1280v/atmega1281v: ? 0 - 4mhz @ 1.8v - 5.5v, 0 - 8mhz @ 2.7v - 5.5v ? atmega2560v/atmega2561v: ? 0 - 2mhz @ 1.8v - 5.5v, 0 - 8mhz @ 2.7v - 5.5v ? atmega640/atmega1280/atmega1281: ? 0 - 8mhz @ 2.7v - 5.5v, 0 - 16mhz @ 4.5v - 5.5v ? atmega2560/atmega2561: ? 0 - 16mhz @ 4.5v - 5.5v 8-bit atmel microcontroller with 64k/128k/256k bytes in-system programmable flash atmega640/v atmega1280/v atmega1281/v atmega2560/v atmega2561/v 2549p?avr?10/2012
2 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 1. pin configurations figure 1-1. tqfp-pinout atmega640/1280/2560 gnd v cc pa0 (ad0) pa1 (ad1) pa2 (ad2) pa3 (ad3) pa4 (ad4) pa5 (ad5) pa6 (ad6) pa7 (ad7) pg2 (ale) a v cc gnd aref pf0 (adc0) pf1 (adc1) pf2 (adc2) pf3 (adc3) pf4 (adc4/tck) pf5 (adc5/tms) pf6 (adc6/tdo) pf7 (adc7/tdi) 100 99 9 8 97 96 95 94 93 92 91 90 8 9 88 8 7 8 6 8 5 8 4 8 3 8 2 8 1 8 0 79 7 8 77 76 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 8 19 20 21 22 23 24 25 75 74 73 72 71 70 69 6 8 67 66 65 64 63 62 61 60 59 5 8 57 56 55 54 53 52 51 26 2 8 29 31 27 36 30 32 35 37 33 34 3 8 39 40 41 42 43 44 45 46 47 4 8 49 50 pk0 (adc 8 /pcint16) pk1 (adc9/pcint17) pk2 (adc10/pcint1 8 ) pk3 (adc11/pcint19) pk4 (adc12/pcint20) pk5 (adc13/pcint21) pk6 (adc14/pcint22) pk7 (adc15/pcint23) (oc2b) ph6 (tosc2) pg3 (tosc1) pg4 reset (t4) ph7 (icp4) pl0 v cc gnd xtal2 xtal1 pl6 pl7 gnd v cc (oc0b) pg5 v cc gnd (rxd2) ph0 (txd2) ph1 (xck2) ph2 (oc4a) ph3 (oc4b) ph4 (oc4c) ph5 (rxd0/pcint 8 ) pe0 (txd0) pe1 (xck0/ain0) pe2 (oc3a/ain1) pe3 (oc3b/int4) pe4 (oc3c/int5) pe5 (t3/int6) pe6 (clko/icp3/int7) pe7 (ss/pcint0) pb0 (sck/pcint1) pb1 (mosi/pcint2) pb2 (miso/pcint3) pb3 (oc2a/pcint4) pb4 (oc1a/pcint5) pb5 (oc1b/pcint6) pb6 (oc0a/oc1c/pcint7) pb7 pc7 (a15) pc6 (a14) pc5 (a13) pc4 (a12) pc3 (a11) pc2 (a10) pc1 (a9) pc0 (a 8 ) pg1 (rd) pg0 (wr) (txd1/int3) pd3 (icp1) pd4 (xck1) pd5 (t1) pd6 (t0) pd7 (scl/int0) pd0 (sda/int1) pd1 (rxd1/int2) pd2 (icp5) pl1 (t5) pl2 (oc5a) pl3 (oc5b) pl4 pj6 (pcint15) pj5 (pcint14) pj4 (pcint13) pj3 (pcint12) pj2 (xck3/pcint11) pj1 (txd3/pcint10) pj0 (rxd3/pcint9) pj7 (oc5c) pl5 index corner
3 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 1-2. cbga-pinout atmega640/1280/2560 n ote: the functions for each pin is the same as for the 100 pin packages shown in figure 1-1 on page 2 . a b c d e f g h j k 1 2345678910 a b c d e f g h j k 1098765432 1 top view bottom view table 1-1. cbga-pinout atmega640/1280/2560 1 2 3 4 5 678 910 a g n d aref pf0 pf2 pf5 pk0 pk3 pk6 g n dvcc b avcc pg5 pf1 pf3 pf6 pk1 pk4 pk7 pa0 pa2 c pe2 pe0 pe1 pf4 pf7 pk2 pk5 pj7 pa1 pa3 d pe3 pe4 pe5 pe6 ph2 pa4 pa5 pa6 pa7 pg2 e pe7 ph0 ph1 ph3 ph5 pj6 pj5 pj4 pj3 pj2 f vcc ph4 ph6 pb0 pl4 pd1 pj1 pj0 pc7 g n d g g n d pb1 pb2 pb5 pl2 pd0 pd5 pc5 pc6 vcc h pb3 pb4 reset pl1 pl3 pl7 pd4 pc4 pc3 pc2 j ph7 pg3 pb6 pl0 xtal2 pl6 pd3 pc1 pc0 pg1 k pb7 pg4 vcc g n d xtal1 pl5 pd2 pd6 pd7 pg0
4 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 1-3. pinout atmega1281/2561 n ote: the large center pad underneath the qf n /mlf package is made of metal and internally con- nected to g n d. it should be soldered or glued to the board to ensure good mechanical stability. if the center pad is left unc onnected, the package might loosen from the board. (rxd0/pcint 8 /pdi) pe0 (txd0/pdo) pe1 (xck0/ain0) pe2 (oc3a/ain1) pe3 (oc3b/int4) pe4 (oc3c/int5) pe5 (t3/int6) pe6 (icp3/clko/int7) pe7 (ss/pcint0) pb0 (oc0b) pg5 (sck/ pcint1) pb1 (mosi/ pcint2) pb2 (miso/ pcint3) pb3 (oc2a/ pcint4) pb4 (oc1a/pcint5) pb5 (oc1b/pcint6) pb6 (oc0a/oc1c/ pcint7 ) pb7 (tosc2) pg3 (tosc1) pg4 reset v cc gnd xtal2 xtal1 (scl/int0) pd0 (sda/int1) pd1 (rxd1/int2) pd2 (txd1/int3) pd3 (icp1) pd4 (xck1) pd5 pa3 (ad3) pa4 (ad4) pa5 (ad5) pa6 (ad6) pa7 (ad7) pg2 (ale) pc7 (a15) pc6 (a14) pc5 (a13) pc4 (a12) pc3 (a11) pc2 (a10) pc1 (a9) pc0 (a 8 ) pg1 (rd) pg0 (wr) a v cc gnd aref pf0 (adc0) pf1 (adc1) pf2 (adc2) pf3 (adc3) pf4 (adc4/tck) pf5 (adc5/tms) pf6 (adc6/tdo) pf7 (adc7/tdi) gnd v cc pa0 (ad0) pa1 (ad1) pa2 (ad2) (t1) pd6 (t0) pd7 index corner 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 64 63 62 61 60 59 5 8 57 56 55 54 53 52 51 50 49 4 8 47 46 45 44 43 42 41 40 39 3 8 37 36 35 34 33 17 1 8 19 20 21 22 23 24 25 26 27 2 8 29 30 31 32
5 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 2. overview the atmega640/1280/1281/2560/2561 is a low-power cmos 8-bit microcontroller based on the avr enhanced risc architecture. by executing pow erful instructions in a single clock cycle, the atmega640/1280/1281/2560/2561 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consumption versus processing speed. 2.1 block diagram figure 2-1. block diagram cpu g n d vcc reset po w e r supervision por / bod & reset w at chdog oscillator w at chdog ti m er oscillator ci r cu i t s / cl o ck gen er at i o n xtal1 xtal2 pc7..0 port c (8) pa7..0 port a (8) port d (8) pd7..0 port b (8) pb7..0 port e ( 8 ) pe7..0 port f (8) pf7..0 port j (8) pj7..0 pg5..0 port g (6) port h (8) ph7..0 port k (8) pk7..0 port l (8) pl7..0 xram t w i spi eeprom jtag 8 bit t/ c 0 8 bit t/ c 2 16 bit t/ c 1 16 bit t/ c 3 sra m flash 16 bit t/ c 4 16 bit t/ c 5 usart 2 usart 1 usart 0 internal bandgap reference analog co m p ar at o r a/ d co n v er t er usart 3 note: shaded part s only available in the 100-pin version. complete functionality for t h e adc, t/ c4, an d t/ c5 o n l y available in the 100-pin version.
6 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the atmel ? avr ? core combines a rich instruction set with 32 general purpose working regis- ters. all the 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulting architecture is more code efficient wh ile achieving throughputs up to ten times faster than conventional cisc microcontrollers. the atmega640/1280/1281/2560/2561 provides the following features: 64k/128k/256k bytes of in-system programmable flash with read- w hile- w rite capabilities, 4kbytes eeprom, 8 kbytes sram, 54/86 general purpose i/o lines, 32 general purpose working registers, real time counter (rtc), six flexible timer/counters with compare modes and p w m, 4 usarts, a byte oriented 2-wire serial interface, a 16-c hannel, 10-bit adc with optional differential input stage with programmable gain, programmable w atchdog timer with internal oscillator, an spi serial port, ieee ? std. 1149.1 compliant jtag test interface, also used for accessing the on- chip debug system and programming and six software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, spi port, and interrupt system to continue functioning. the power-down mode saves the register contents but freezes the oscillator, disabling all other ch ip functions until the next interr upt or hardware reset. in power- save mode, the asynchronous timer continues to run, allowing the user to maintain a timer base while the rest of the device is sleeping. the adc n oise reduction mode stops the cpu and all i/o modules except asynchronous timer and adc, to minimize switching noise during adc conversions. in standby mode, the crystal/resonato r oscillator is running while the rest of the device is sleeping. this allows very fast st art-up combined with lo w power consumption. in extended standby mode, bo th the main oscillator and the asynchronous ti mer continue to run. atmel offers the qtouch ? library for embedding capacitive touch buttons, sliders and wheels- functionality into avr microcontrollers. the patented charge-transfer signal acquisition offersrobust sensing and includes fully debounced reporting of touch keys and includes adjacent keysuppression ? (aks ? ) technology for unambiguous detection of key events. the easy-to-use qtouch suite toolchain allows you to explore, develop and debug your own touch applications. the device is manufactured using atmel?s high- density nonvolatile memory technology. the on- chip isp flash allows the prog ram memory to be repr ogrammed in-system th rough an spi serial interface, by a conventional nonvolatile memory programmer, or by an on-chip boot program running on the avr core. the boot program can use any interface to download the application program in the applicatio n flash memory. software in the boot flash section will continue to run while the application flash section is updated, providing true read- w hile- w rite operation. by combining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel atmega640/1280/1281/2560/2561 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the atmega640/1280/1281/2560/2561 avr is supported with a full suite of program and sys- tem development tools including: c compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits.
7 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 2.2 comparison between atme ga1281/2561 and at mega640/1280/2560 each device in the atmega640/1280/1281/2560/2561 family differs only in memory size and number of pins. table 2-1 summarizes the different configurations for the six devices. 2.3 pin descriptions 2.3.1 vcc digital supply voltage. 2.3.2 gnd ground. 2.3.3 port a (pa7..pa0) port a is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port a output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port a pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port a pins are tri-stated when a reset condition becomes active, even if the clock is not running. port a also serves the functions of various special features of the atmega640/1280/1281/2560/2561 as listed on page 78 . 2.3.4 port b (pb7..pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b has better driving capabilities than the other ports. port b also serves the functions of various special features of the atmega640/1280/1281/2560/2561 as listed on page 79 . 2.3.5 port c (pc7..pc0) port c is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port c output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port c pi ns that are externally pulled lo w will source current if the pull-up table 2-1. configuration summary device flash eeprom ram general purpose i/o pins 16 bits resolution pwm channels serial usarts adc channels atmega640 64kb 4kb 8kb 86 12 4 16 atmega1280 128kb 4kb 8kb 86 12 4 16 atmega1281 128kb 4kb 8kb 54 6 2 8 atmega2560 256kb 4kb 8kb 86 12 4 16 atmega2561 256kb 4kb 8kb 54 6 2 8
8 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 resistors are activated. the port c pins are tri-stated when a reset condition becomes active, even if the clock is not running. port c also serves the functions of special features of the atmega640/1280/1281/2560/2561 as listed on page 82 . 2.3.6 port d (pd7..pd0) port d is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port d pi ns that are externally pulled lo w will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of various special features of the atmega640/1280/1281/2560/2561 as listed on page 83 . 2.3.7 port e (pe7..pe0) port e is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port e output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port e pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port e pins are tri-stated when a reset condition becomes active, even if the clock is not running. port e also serves the functions of various special features of the atmega640/1280/1281/2560/2561 as listed on page 86 . 2.3.8 port f (pf7..pf0) port f serves as analog inputs to the a/d converter. port f also serves as an 8-bit bi-directional i/o port, if the a/d converter is not used. port pins can provide internal pull-up resistors (selected for each bit). the port f output buffers have sym- metrical drive characteristics with both high sink and source capa bility. as inputs, port f pins that are externally pulled low will source current if the pull-up resistors are ac tivated. the port f pins are tri-stated when a reset condition becomes active, even if the clock is not running. if the jtag interface is enabled, the pull-up resistors on pins pf7( tdi), pf5(tms), and pf4(tck) will be activated even if a reset occurs. port f also serves the functions of the jtag interface. 2.3.9 port g (pg5..pg0) port g is a 6-bit i/o port with internal pull-up resistors (selected for each bit). the port g output buffers have symmetrical drive characteristic s with both high sink and source capability. as inputs, port g pins that are externally pulled lo w will source current if the pull-up resistors are activated. the port g pins are tri-stated when a reset condition becomes active, even if the clock is not running. port g also serves the functions of various special features of the atmega640/1280/1281/2560/2561 as listed on page 90 . 2.3.10 port h (ph7..ph0) port h is a 8-bit bi-directional i/o port with inte rnal pull-up resistors (selected for each bit). the port h output buffers have symmetrical drive c haracteristics with bot h high sink and source capability. as inputs, port h pi ns that are externally pulled lo w will source current if the pull-up
9 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 resistors are activated. the port h pins are tri-stated when a reset condition becomes active, even if the clock is not running. port h also serves the functions of various special features of the atmega640/1280/2560 as listed on page 92 . 2.3.11 port j (pj7..pj0) port j is a 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port j output buffers have symmetrical drive characteristics with both high sink and source capa- bility. as inputs, port j pins that are externally pulled low will source current if the pull-up resistors are activated. the port j pins are tr i-stated when a reset condition becomes active, even if the clock is not running. port j also serves the functions of various special features of the atmega640/1280/2560 as listed on page 94 . 2.3.12 port k (pk7..pk0) port k serves as analog inputs to the a/d converter. port k is a 8-bit bi-directional i/o port with inte rnal pull-up resistors (selected for each bit). the port k output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port k pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port k pins are tri-stated when a reset condition becomes active, even if the clock is not running. port k also serves the functions of vari ous special features of the atmega640/1280/2560 as listed on page 96 . 2.3.13 port l (pl7..pl0) port l is a 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port l output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port l pins that are externally pulled low will source current if the pull-up resistors are activated. the port l pins are tri-stated when a reset condition becomes active, even if the clock is not running. port l also serves the functions of variou s special features of the atmega640/1280/2560 as listed on page 98 . 2.3.14 reset reset input. a low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not runni ng. the minimum pulse length is given in ?system and reset characteristics? on page 372 . shorter pulses are not guaranteed to generate a reset. 2.3.15 xtal1 input to the inverting oscillato r amplifier and input to the in ternal clock operating circuit. 2.3.16 xtal2 output from the invert ing oscillator amplifier.
10 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 2.3.17 avcc avcc is the supply voltage pin for port f and the a/d converter. it should be externally con- nected to v cc , even if the adc is not used. if the adc is used, it should be connected to v cc through a low-pass filter. 2.3.18 aref this is the analog reference pin for the a/d converter.
11 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 3. resources a comprehensive set of development tools a nd application notes, and datasheets are available for download on http://www.atmel.com/avr . 4. about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documen- tation for more details. these code examples assume that the part specific header file is included before compilation. for i/o registers located in extended i/o map, "i n ", "out", "sbis", "sbic", "cbi", and "sbi" instructions must be replaced with instructio ns that allow access to extended i/o. typically "lds" and "sts" combined with "sbrs", "sbrc", "sbr", and "cbr". 5. data retention reliability qualification results show that the pr ojected data retention failure rate is much less than 1 ppm over 20 years at 85c or 100 years at 25c. 6. capacitive touch sensing the atmel ? qtouch ? library provides a simple to use so lution to realize touch sensitive inter- faces on most atmel avr ? microcontrollers. the qtouch library includes support for the qtouch and qmatrix ? acquisition methods. touch sensing can be added to any application by linking the appropriate atmel qtouch library for the avr microcontroller. this is done by using a simple set of apis to define the touch chan- nels and sensors, and then calling the touch sens ing api?s to retrieve the channel information and determine the touch sensor states. the qtouch library is free and downloadable from the atmel website at the following location: www.atmel.com/qtouchlibrary . for implementation details and other information, refer to the atmel qtouch library user guide - also available for download from the atmel website.
12 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 7. avr cpu core 7.1 introduction this section discusses the avr core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. 7.2 architectural overview figure 7-1. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a sing le level pipelining. w hile one instruction is being executed, the next instruc- tion is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. fl ash pr o g r am memory instruction re g i st e r instruction decoder pr o g r am co u n t er control lines 32 x 8 gen er al pu r p o se re g i st e r s alu st a t u s and cont rol i/ o lines eeprom dat a bus 8-bit dat a sra m direct addressing indirect addressing interrupt unit spi unit w at chdog ti m er analog comparat or i/ o module 2 i/ o module1 i/ o module n
13 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the fast-access register file contains 32 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle ar ithmetic logic unit (alu ) operation. in a typ- ical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16-b it indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic opera- tion, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and uncon ditional jump and call instructions, able to directly address the whole address space. most avr instructions have a single 16-bit word for- mat. every program memory address contains a 16-bit or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the application program section. both sections have dedicated lock bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the to tal sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control r egisters in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector posi- tion. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functi ons as control regis- ters, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. in addition, the atmega640/1280/1281/2560/2561 has extended i/o space from 0x60 - 0x1ff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 7.3 alu ? arithm etic logic unit the high-performance avr alu operates in dire ct connection with all the 32 general purpose working registers. w ithin a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set summary? on page 416 for a detailed description.
14 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 7.4 status register the status register contains information about the result of the most recently executed arithme- tic instruction. this information can be used for altering program flow in order to perform conditional operations. n ote that the status register is updated after all alu operations, as specified in the ?instruction set summary? on page 416 . this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. 7.4.1 sreg ? avr status register the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for th e interrupts to be enabled. the individual inter- rupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i-bit can also be set and cleared by the application with the sei and cli instructions, as described in the ?instruction set summary? on page 416 . ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (b it store) use the t-bit as source or desti- nation for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in so me arithmetic operations. half carry is useful in bcd arithmetic. see the ?instruction set summary? on page 416 for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the n egative flag n and the two?s complement overflow flag v. see the ?instruction set summary? on page 416 for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v suppor ts two?s complement arithmetics. see the ?instruction set summary? on page 416 for detailed information. ? bit 2 ? n: negative flag the n egative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set summary? on page 416 for detailed information. bit 76543210 0x3f (0x5f) ithsvnzcsreg read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
15 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set summary? on page 416 for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logic operation. see the ?instruction set summary? on page 416 for detailed information. 7.5 general purpose register file the register file is optimized for the avr enhanc ed risc instruction set. in order to achieve the required performance and flex ibility, the following in put/output schemes ar e supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 7-2 shows the structure of the 32 general purpose working registers in the cpu. figure 7-2. avr cpu general purpose w orking registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 7-2 , each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being physically imple- mented as sram locations, this memory organization provides great flexibility in access of the registers, as the x-, y- and z-pointer registers can be set to index any register in the file. 7.5.1 the x-register, y-register, and z-register the registers r26..r31 have some added functions to their general purpose usage. these reg- isters are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 7-3 on page 16 . 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f w orking r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
16 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 7-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the ?instruction set summary? on page 416 for details). 7.6 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer register always points to the top of the stack. n ote that the stack is implemented as growing from higher memory loca- tions to lower memory locations. this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are located. this stack space in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. the stack pointer must be set to point above 0x0200. the initial value of the stack pointer is the last address of the internal sram. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by two for atmega640/1280/1281 and three for atmega2560/2561 when the return address is pushed onto the stack with subroutine call or interrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by two for atmega640/1280/1281 and three for atmega2560/2561 when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8- bit registers in the i/o space. the number of bits actually used is implementation dependent. n ote that the data space in some implementa- tions of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x-register 707 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 707 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 70 7 0 r31 (0x1f) r30 (0x1e) bit 151413121110 9 8 0x3e (0x5e) sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph 0x3d (0x5d) sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 1 0 0 0 0 1 11111111
17 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 7.6.1 rampz ? extended z-pointer register for elpm/spm for elpm/spm instructions, the z-pointer is a concatenation of rampz, zh, and zl, as shown in figure 7-4. n ote that lpm is not affected by the rampz setting. figure 7-4. the z-pointer used by elpm and spm the actual number of bits is implementation depen dent. unused bits in an implementation will always read as zero. for compatibility with future devices, be su re to write these bits to zero. 7.6.2 eind ? extended indirect register for eicall/eijmp instructions, the indirect-pointer to the subroutine/routine is a concatenation of ei n d, zh, and zl, as shown in figure 7-5. n ote that icall and ijmp are not affected by the ei n d setting. figure 7-5. the indirect-pointer used by eicall and eijmp the actual number of bits is implementation depen dent. unused bits in an implementation will always read as zero. for compatibility with future devices, be su re to write these bits to zero. 7.7 instruction execution timing this section describes the general access timi ng concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. n o internal clock division is used. figure 7-6 on page 18 shows the parallel instruction fetches and instruction executions enabled by the harvard architecture and the fast-access r egister file concept. this is the basic pipelin- ing concept to obtain up to 1 mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. bit 765432 1 0 0x3b (0x5b) rampz7 rampz6 rampz5 rampz4 rampz3 rampz2 rampz1 rampz0 rampz read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value000000 0 0 bit (individually) 707070 rampz zh zl bit (z-pointer) 23 16 15 8 7 0 bit 765432 1 0 0x3c (0x5c) eind7 eind6 eind5 eind4 ei nd3 eind2 eind1 eind0 eind read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value000000 0 0 bit (individually) 707070 eind zh zl bit (indirect- pointer) 23 16 15 8 7 0
18 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 7-6. the parallel instruction fetches and instruction executions figure 7-7 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destina- tion register. figure 7-7. single cycle alu operation 7.8 reset and inte rrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in orde r to enable the interrupt. depending on the program counter value, interrupts may be automatically disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see the section ?memory program- ming? on page 335 for details. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 105 . the list also determines the priority levels of the different interrupts. the lower the address the higher is the priority level. reset has the highest priority, and next is i n t0 ? the external interrupt request 0. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the mcu control register (mcucr). refer to ?interrupts? on page 105 for more informa- tion. the reset vector can also be moved to the start of the boot flash section by programming the bootrst fuse, see ?memory programming? on page 335 . w hen an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are dis- abled. the user software can write logic one to the i-bit to enable nested interrupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
19 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 there are basically two types of interrupts. the fi rst type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vec- tor in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt fl ag will be set and remember ed until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is clea red, the corres ponding interrupt fl ag(s) will be set and remembered until the global interrupt enable bit is set, and will then be exec uted by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the in terrupt will not be triggered. w hen the avr exits from an interrupt, it will alwa ys return to the main program and execute one more instruction before any pending interrupt is served. n ote that the status register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. w hen using the cli instruction to disable interrupts, the interrup ts will be immediately disabled. n o interrupt will be executed afte r the cli instruction, even if it occurs simultaneously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. w hen using the sei instruction to enable interrupt s, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ __disable_interrupt(); eecr |= (1< 20 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 7.8.1 interrupt response time the interrupt execution response for all the enab led avr interrupts is five clock cycles minimum. after five clock cycles the program vector address for the actual interrupt handling routine is exe- cuted. during these five clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. if an interrupt occurs w hen the mcu is in sleep mode, the interrupt exe- cution response time is increased by five cloc k cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine takes fi ve clock cycles. during these five clock cycles, the program counter (three bytes) is popped back from the stack, the stack pointer is incre- mented by three, and the i-bit in sreg is set. assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) c code example __enable_interrupt(); /* set global interrupt enable */ __sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
21 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 8. avr memories this section describes the different memories in the atmega640/1280/1281/2560/2561. the avr architecture has two main memory spaces, the data memory and the program memory space. in addition, the atme ga640/1280/1281/2560 /2561 features an eeprom memory for data storage. all three memory spaces are linear and regular. 8.1 in-system reprogrammable flash program memory the atmega640/1280/1281/2560/2561 contains 64k/128k/256k bytes on-chip in-system reprogrammable flash memory for program storage, see figure 8-1 . since all avr instructions are 16 bit or 32 bit wide, the flash is organiz ed as 32k/64k/128k 16. for software security, the flash program memory space is divided into two sections, boot program section and appli- cation program section. the flash memory has an endurance of at least 10,000 write/erase cycles. the atmega640/1280/1281/2560/2561 program counter (pc) is 15/16/17 bits wide, thus addressing the 32k/64k/128k program memory locations. the operation of boot program section and asso- ciated boot lock bits for software pr otection are described in detail in ?boot loader support ? read- w hile- w rite self-programming? on page 317 . ?memory programming? on page 335 con- tains a detailed description on flash data seri al downloading using the spi pins or the jtag interface. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory instruction description and elpm - extended load program memory instruction description). timing diagrams for instruction fetch and execution are presented in ?instruction execution tim- ing? on page 17 . 8.2 sram data memory figure 8-2 on page 23 shows how the atmega640/1280/1281/2560/2561 sram memory is organized. the atmega640/1280/1281/2560/2561 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in the opcode for the i n and out instruc- tions. for the extended i/o space from $060 - $1ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the first 4,608/8,704 data memory locations address both the register file, the i/o memory, extended i/o memory, and the internal data sr am. the first 32 locations address the register file, the next 64 location the standard i/o memory, then 416 locations of extended i/o memory and the next 8,192 locations address the internal data sram. figure 8-1. program flash memory map address (hex) 0 application flash section boot flash section 0x7fff/0xffff/0x1ffff
22 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 an optional external data sram can be used with the atmega640/1280/1281/2560/2561. this sram will occupy an area in the remaining addr ess locations in the 64k address space. this area starts at the address following the internal sram. the register file, i/o, extended i/o and internal sram occupies the lowest 4,608/8, 704 bytes, so when using 64kbytes (65,536 bytes) of external memory, 60,478/56,832 bytes of external memory are available. see ?external memory interface? on page 28 for details on how to take advantage of the external memory map. w hen the addresses accessing the sram memory space exceeds the internal data memory locations, the external data sram is accessed using the same instructions as for the internal data memory access. w hen the internal data memories are accessed, the read and write strobe pins (pg0 and pg1) are inacti ve during the whole access cycl e. external sram operation is enabled by setting the sre bit in the xmcra register. accessing external sram takes one additional clock cycle per byte compared to access of the internal sram. this means that the commands ld, st, lds, sts, ldd, std, push, and pop take one additional clock cycle. if the stack is placed in external sram, interrupts, subroutine calls and returns take three clock cycles extra because the three-byte program counter is pushed and popped, and external memory access does not take advantage of the internal pipe- line memory access. w hen external sram interface is used with wait-state, one-byte external access takes two, three, or four additional cl ock cycles for one, two, and three wait-states respectively. interrupts, subroutine calls and returns will need five, seven, or nine clock cycles more than specified in the instruction set manual for one, two, and three wait-states. the five different addressing modes for the data memory cover: direct, indirect with displace- ment, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y-register or z-register. w hen using register indirect addressing modes with automatic pre-decrement and post-incre- ment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, and the 4,196/8,192 bytes of internal data sram in the atmega640/1280/1281/2560/2561 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 15 .
23 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 8.2.1 data memory access times this section describes the general access timi ng concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 8-3 . figure 8-3. on-chip data sram access cycles 8.3 eeprom data memory the atmega640/1280/1281/2560/2561 contains 4kbytes of data eeprom memory. it is orga- nized as a separate data spac e, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specif ying the eeprom address registers, the eeprom data register, and the eeprom control register. for a detailed description of spi, jtag and parallel data downloading to the eeprom, see ?serial downloading? on page 349 , ?programming via the jtag interface? on page 354 , and ?programming the eeprom? on page 343 respectively. figure 8-2. data memory map address (hex) 0 - 1f 32 registers 20 - 5f 64 i/o registers 60 - 1ff 416 external i/o registers 200 internal sram (8192 8) 21ff 2200 external sram (0 - 64k 8) ffff clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
24 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 8.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space, see ?register description? on page 35 . the write access time for the eeprom is given in table 8-1 . a self-timing function, however, lets the user software detect when the next byte can be written. if the user code contains instruc- tions that write the eeprom, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on po wer-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom co rruption? on page 26. for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be followed. see the description of the eeprom cont rol register for details on this; ?register description? on page 35 . w hen the eeprom is read, the cpu is halted for four clock cycles before the next in struction is executed. w hen the eeprom is written, the cpu is halted for two clock cycles before the next instruction is executed. the calibrated oscillator is used to time the eeprom accesses. table 8-1 lists the typical pro- gramming time for eeprom access from the cpu. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (for example by disabling inter- rupts globally) so that no inte rrupts will occur during execution of these functi ons. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait fo r any ongoing spm co mmand to finish. table 8-1. eeprom programming time symbol number of calibrated rc osc illator cycles typ programming time eeprom write (from cpu) 26,368 3.3ms
25 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. assembly code example (1) eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eempe sbi eecr,eempe ; start eeprom write by setting eepe sbi eecr,eepe ret c code example (1) void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 26 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the next code examples show assembly and c functions for reading the eeprom. the exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. n ote: 1. see ?about code examples? on page 11. 8.3.2 preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupted because the supply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eepr om, and the same design so lutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. sec- ondly, the cpu itself can execute instructions incorrectly, if the supp ly voltage is too low. eeprom data corruption can ea sily be avoided by followin g this design recommendation: keep the avr reset active (low) during periods of insufficient power su pply voltage. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress , the write operation will be com- pleted provided that the power supply voltage is sufficient. assembly code example (1) eeprom_read: ; wait for completion of previous write sbic eecr,eepe rjcmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example (1) unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 27 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 8.4 i/o memory the i/o space definition of the atmega640/1280/1281/2560/2561 is shown in ?register sum- mary? on page 411 . all atmega640/1280/1281/2560/2561 i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-acce ssible using the sbi an d cbi instructions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the ?instruction set summary? on page 416 for more details. w hen using the i/o spe- cific commands i n and out, the i/o addresses 0x00 - 0x3f must be used. w hen addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega640/1280/1281/2560/2561 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the i n and out instruc- tions. for the extended i/o space from 0x60 - 0x1ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. n ote that, unlike most other avrs, the cbi and sbi instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work with reg- isters 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. 8.4.1 general purpose i/o registers the atmega640/1280/1281/2560/2561 contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for storing global variables and status flags. general pu rpose i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. see ?register description? on page 35 .
28 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 9. external memory interface w ith all the features the external memory interf ace provides, it is well suited to operate as an interface to memory devices such as external sram and flash, and peripherals such as lcd- display, a/d, and d/a. the main features are: ? four different wait-s tate settings (includi ng no wait-state) ? independent wait-state setting fo r different external memory sect ors (configurable sector size) ? the number of bits dedicated to address high byte is selectable ? bus keepers on data lines to minimi ze current consumption (optional) 9.1 overview w hen the external memory (xmem) is enabled , address space outside the internal sram becomes available using the dedicated external memory pins (see figure 1-3 on page 4 , table 13-3 on page 78 , table 13-9 on page 82 , and table 13-21 on page 90 ). the memory configura- tion is shown in figure 9-1 . figure 9-1. external memory with sector select memory confi g uration a 0x0000 0x21ff extern a l memory (0 - 60k x 8) 0xffff intern a l memory srl[2..0] srw11 srw10 srw01 srw00 lower s ector upper s ector 0x2200
29 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 9.1.1 using the external memory interface the interface consists of: ? ad7:0: multiplexed low-order address bus and data bus ? a15:8: high-order address bus (configurable number of bits) ? ale: address latch enable ?rd : read strobe ? w r : w rite strobe the control bits for the external memory interface are located in two registers, the external memory control register a ? xmcra, and the external memory control register b ? xmcrb. w hen the xmem interface is enabled, the xmem in terface will override th e setting in the data direction registers that corresponds to the ports dedicated to the xmem interface. for details about the port override, see the alternate functions in section ?i/o-ports? on page 70 . the xmem interface will auto-detect wh ether an access is internal or extern al. if the access is external, the xmem interface will output address, data, and the control si gnals on the ports according to fig- ure 9-3 on page 31 (this figure shows the wave forms without wait-states). w hen ale goes from high-to-low, there is a valid address on ad7:0. ale is low during a data transfer. w hen the xmem interface is enabled, also an internal access will cause ac tivity on address, data and ale ports, but the rd and w r strobes will not toggle during internal access. w hen the external memory interface is disabled, the normal pin and data direction settings are used. n ote that when the xmem interface is disabled, the address space above the internal sram boundary is not mapped into the internal sram. figure 9-2 on page 30 illustrates how to connect an external sram to the avr using an octal latch (typically ?74 573? or equivalent) which is transparent when g is high. 9.1.2 address latch requirements due to the high-speed operation of the xram interface, the address latch must be selected with care for system frequencies above 8mhz @ 4v and 4mhz @ 2.7v. w hen operating at condi- tions above these frequencies, the typical old style 74hc series latch becomes inadequate. the external memory interface is designed in compliance to the 74ahc series latch. however, most latches can be used as long they comply with the main timing parameters. the main parameters for the address latch are: ? d to q propagation delay (t pd ) ? data setup time before g low (t su ) ? data (address) hold time after g low ( th ) the external memory interface is designed to guaranty minimum address hold time after g is asserted low of t h = 5ns. refer to t laxx_ld /t llaxx_st in ?external data memory timing? tables 31- 11 through tables 31-18 on pages 379 - 382 . the d-to-q propagation delay (t pd ) must be taken into consideration when calculating the access time requirement of the external component. the data setup time before g low (t su ) must not exceed address valid to ale low (t avllc ) minus pcb wiring delay (dependent on the capacitive load).
30 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 9-2. external sram connected to the avr 9.1.3 pull-up and bus-keeper the pull-ups on the ad7:0 ports may be activated if the corresponding port register is written to one. to reduce power consumption in sleep mode, it is recommended to disable the pull-ups by writing the port register to zero before entering sleep. the xmem interface also provides a bus-keeper on the ad7:0 lines. the bus-keeper can be dis- abled and enabled in software as described in ?xmcrb ? external memo ry control register b? on page 38 . w hen enabled, the bus-keeper will keep th e previous value on the ad7:0 bus while these lines are tri-stated by the xmem interface. 9.1.4 timing external memory devices have different timing requirements. to meet these requirements, the xmem interface provides four different wait-states as shown in table 9-3 on page 38 . it is impor- tant to consider the timing specification of the external memory device before selecting the wait- state. the most important parameters are the access time for the external memory compared to the set-up requirement. the access time for the external memory is defined to be the time from receiving the chip selec t/address until the data of this address actually is driven on the bus. the access time cannot exceed the time from the ale pulse must be asserted low until data is stable during a read sequence (see t llrl + t rlrh - t dvrh in tables 31-11 through tables 31-18 on pages 379 - 382 ). the different wait-states are set up in software. as an additional feature, it is possible to divide the external memory s pace in two sectors with indivi dual wait-state settings. this makes it possible to connect two different memory devices with different timing requirements to the same xmem interface. for xmem interface timing details, please refer to table 31-11 on page 379 to table 31-18 on page 382 and figure 31-9 on page 382 to figure 31-12 on page 384 in the ?external data memory timing? on page 379 . n ote that the xmem interface is asynchronous and that the waveforms in the following figures are related to the internal system clock. t he skew between the internal and external clock (xtal1) is not guarantied (varies between devices temperature, and supply voltage). conse- quently, the xmem interface is not suited for synchronous operation. d[7:0] a[7:0] a[15:8] rd wr sram dq g ad7:0 ale a15:8 rd wr avr
31 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 9-3. external data memory cycles without w ait-state (sr w n1=0 and sr w n0=0) (1) n ote: 1. sr w n1 = sr w 11 (upper sector) or sr w 01 (lower sector), sr w n0 = sr w 10 (upper sector) or sr w 00 (lower sector). the ale pulse in period t4 is only present if the next instruction accesses the ram (internal or external). figure 9-4. external data memory cycles with sr w n1 = 0 and sr w n0 = 1 (1) n ote: 1. sr w n1 = sr w 11 (upper sector) or sr w 01 (lower sector), sr w n0 = sr w 10 (upper sector) or sr w 00 (lower sector). the ale pulse in period t5 is only present if the next instruction accesses the ram (internal or external). ale t1 t2 t3 w rite read w r t4 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) xxxxx xxxxxxxx ale t1 t2 t3 w rite read w r t5 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) t4
32 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 9-5. external data memory cycles with sr w n1 = 1 and sr w n0 = 0 (1) n ote: 1. sr w n1 = sr w 11 (upper sector) or sr w 01 (lower sector), sr w n0 = sr w 10 (upper sector) or sr w 00 (lower sector). the ale pulse in period t6 is only present if the next instruction accesses the ram (internal or external). figure 9-6. external data memory cycles with sr w n1 = 1 and sr w n0 = 1 (1) n ote: 1. sr w n1 = sr w 11 (upper sector) or sr w 01 (lower sector), sr w n0 = sr w 10 (upper sector) or sr w 00 (lower sector). the ale pulse in period t7 is only present if the next instruction accesses the ram (internal or external). 9.1.5 using all locations of external memory smaller than 64kbytes since the external memory is mapped after the internal memory as shown in figure 9-1 on page 28 , the external memory is not addressed when addressing the first 8,704 bytes of data space. it may appear that the first 8,704 bytes of the external memory are inaccessible (external memory addresses 0x0000 to 0x21ff). however, when connecting an external memory smaller than 64kbytes, for example 32kbytes, these locations are easily accessed simply by addressing from address 0x8000 to 0xa1ff. since the external me mory address bit a15 is not connected to the external memory, addresses 0x 8000 to 0xa1ff will ap pear as addresses 0x 0000 to 0x21ff for the external memory. addressing above address 0xa1ff is not recommended, since this will address an external memory location that is al ready accessed by another (lower) address. to the application software, the external 32kbytes memory w ill appear as one linear 32kbytes ale t1 t2 t3 w rite read w r t6 a15:8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) system clock (clk cpu ) t4 t5 ale t1 t2 t3 write read wr t7 a15: 8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data prev. data address data prev. data address da7:0 (xmbk = 1) s ystem clock (clk cpu ) t4 t5 t6
33 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 address space from 0x2200 to 0xa1ff. this is illustrated in figure 9-7 . figure 9-7. address map with 32kbytes external memory 9.1.6 using all 64kbytes locations of external memory since the external memory is mapped af ter the internal memory as shown in figure 9-1 on page 28 , only 56kbytes of external memory is avail able by default (address space 0x0000 to 0x21ff is reserved for internal memory). however, it is possible to take advantage of the entire external memory by masking the higher address bits to zero. this can be done by using the xmmn bits and control by software the most significant bits of the address. by setting port c to output 0x00, and releasing the most si gnificant bits for normal port pin operation, the memory interface will address 0x0000 - 0x2fff. see the following code examples. care must be exercised using this option as most of the memory is masked away. 0x0000 0x21ff 0x2200 0x7fff 0x8000 0x90ff 0x9100 0x0000 0x7fff internal memory avr memory map external 32k sram external memory
34 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. assembly code example (1) ; offset is defined to 0x4000 to ensure ; external memory access ; configure port c (address high byte) to ; output 0x00 when the pins are released ; for normal port pin operation ldi r16, 0xff out ddrc, r16 ldi r16, 0x00 out portc, r16 ; release pc7:6 ldi r16, (1< 35 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 9.2 register description 9.2.1 eeprom registers 9.2.1.1 eearh and eearl ? the eeprom address register ? bits 15:12 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bits 11:0 ? eear8:0: eeprom address the eeprom address registers ? eearh and eearl specify the eeprom address in the 4kbytes eeprom space. the eeprom dat a bytes are addressed linearly between 0 and 4096. the initial value of eear is undefined. a proper valu e must be written before the eeprom may be accessed. 9.2.1.2 eedr ? the eeprom data register ? bits 7:0 ? eedr7:0: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address given by the eear regi ster. for the eeprom read operation, the eedr contains the data read out from the eeprom at the add ress given by eear. 9.2.1.3 eecr ? the eeprom control register ? bits 7:6 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bit setting define s which programming acti on that will be trig- gered when writing eepe. it is possible to program data in one atomic operation (erase the old value and program the new value) or to split the erase and w rite operations in two different operations. the programming times for the different modes are shown in table 9-1 on page 36 . w hile eepe is set, any write to eepmn will be ignored. during reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. bit 15141312 11 10 9 8 0x22 (0x42) ????eear11eear10eear9eear8eearh 0x21 (0x41) eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 7654 3 2 10 read/ w rite rrrrr/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value0000x xxx xxxx x x xx bit 76543210 0x20 (0x40) msb lsb eedr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543 210 0x1f (0x3f) ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/ w rite r r r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 x x 0 0 x 0
36 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 3 ? eerie: eeprom ready interrupt enable w riting eerie to one enables the eeprom ready interrupt if the i bit in sreg is set. w riting eerie to zero disables the interrupt. the eeprom ready interrupt generates a constant inter- rupt when eepe is cleared. ? bit 2 ? eempe: eeprom master programming enable the eempe bit determines whether setting eepe to one causes the eeprom to be written. w hen eempe is set, setting eepe wit hin four clock cycles will writ e data to the eeprom at the selected address if eempe is zero , setting eepe will have no effect. w hen eempe has been written to one by software, ha rdware clears the bit to zero after four clock cycles. see the description of the eepe bit fo r an eeprom write procedure. ? bit 1 ? eepe: eeprom programming enable the eeprom w rite enable signal eepe is the write strobe to the eeprom. w hen address and data are correctly set up, the eepe bit must be written to one to write the value into the eeprom. the eempe bit must be written to one be fore a logical one is written to eepe, other- wise no eeprom write takes pl ace. the following pr ocedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. w ait until eepe becomes zero. 2. w ait until spme n in spmcsr becomes zero. 3. w rite new eeprom address to eear (optional). 4. w rite new eeprom data to eedr (optional). 5. w rite a logical one to the eempe bit wh ile writing a zero to eepe in eecr. 6. w ithin four clock cycles after setting eempe, write a logical one to eepe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is co mpleted before initiating a new eeprom write. step 2 is only relevant if the software contai ns a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see ?memory pro- gramming? on page 335 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master w rite enable will time-out. if an interrupt routine accessing the eeprom is interrupting another eeprom acce ss, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. w hen the write access time has elapsed, the ee pe bit is cleared by hardware. the user soft- ware can poll this bit and wait for a zero before writing the next byte. w hen eepe has been set, the cpu is halted for two cycles before the next instruction is executed. table 9-1. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4ms erase and w rite in one operation (atomic operation) 0 1 1.8ms erase only 1 0 1.8ms w rite only 1 1 ? reserved for future use
37 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the read strobe to the eeprom. w hen the correct address is set up in the eear register, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and th e requested data is available immediately. w hen the eeprom is read, the cpu is halted for four cycles before the next instruction is executed. the user should poll the eepe bit before starting the read operation. if a write operation is in progress, it is neither possi ble to read the eeprom, nor to change the eear register. 9.3 general purpose registers 9.3.1 gpior2 ? general purpose i/o register 2 9.3.2 gpior1 ? general purpose i/o register 1 9.3.3 gpior0 ? general purpose i/o register 0 9.4 external memory registers 9.4.1 xmcra ? external memory control register a ? bit 7 ? sre: external sram/xmem enable w riting sre to one enables the external memory interface.the pin functions ad7:0, a15:8, ale, w r , and rd are activated as the alternate pin functions. the sre bit overrides any pin direction settings in the respective data direction registers. w riting sre to zero, disables the external memory interface and the normal pin and data direction settings are used. ? bit 6:4 ? srl2:0: wait-state sector limit it is possible to configure different wait-states for different external memory addresses. the external memory address space can be divided in two sectors that have separate wait-state bits. the srl2, srl1, and srl0 bits select the split of the sectors, see table 9-2 on page 38 and bit 76543210 0x2b (0x4b) msb lsb gpior2 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x2a (0x4a) msb lsb gpior1 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1e (0x3e) msb lsb gpior0 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 ?(0x74)? sre srl2 srl1 srl0 srw11 srw10 srw01 srw00 xmcra read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
38 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 9-1 on page 28 . by default, the srl2, srl1, and srl0 bits are set to zero and the entire external memory address space is treated as one sector. w hen the entire sram address space is configured as one sector, the wait-states are configured by the sr w 11 and sr w 10 bits. ? bit 3:2 ? srw11, srw10: wait-state select bits for upper sector the sr w 11 and sr w 10 bits control the number of wait-states for the upper sector of the exter- nal memory address space, see table 9-3 . ? bit 1:0 ? srw01, srw00: wait-state select bits for lower sector the sr w 01 and sr w 00 bits control the number of wait-states for the lower sector of the exter- nal memory address space, see table 9-3 . n ote: 1. n = 0 or 1 (lower/upper sector). for further details of the timing and wait-states of the external memory interface, see figures 9-3 through figures 9-6 for how the setting of the sr w bits affects the timing. 9.4.2 xmcrb ? external memory control register b table 9-2. sector limits with different settings of srl2:0 srl2 srl1 srl0 sector limits 00x lower sector = n /a upper sector = 0x2200 - 0xffff 010 lower sector = 0x2200 - 0x3fff upper sector = 0x4000 - 0xffff 011 lower sector = 0x2200 - 0x5fff upper sector = 0x6000 - 0xffff 100 lower sector = 0x2200 - 0x7fff upper sector = 0x8000 - 0xffff 101 lower sector = 0x2200 - 0x9fff upper sector = 0xa000 - 0xffff 110 lower sector = 0x2200 - 0xbfff upper sector = 0xc000 - 0xffff 111 lower sector = 0x2200 - 0xdfff upper sector = 0xe000 - 0xffff table 9-3. w ait states (1) srwn1 srwn0 wait states 00 n o wait-states 01 w ait one cycle during read/write strobe 10 w ait two cycles during read/write strobe 11 w ait two cycles during read/write and wait one cycle before driving out new address bit 765 4 3 210 (0x75) xmbk ? ? ? ? xmm2 xmm1 xmm0 xmcrb read/ w rite r/ w rr r rr/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
39 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 7? xmbk: external memory bus-keeper enable w riting xmbk to one enables the bus keeper on the ad7:0 lines. w hen the bus keeper is enabled, ad7:0 will keep the last driven value on the lines even if the xmem interface has tri- stated the lines. w riting xmbk to zero disables the bus keeper. xmbk is not qualified with sre, so even if the xmem in terface is disabled, the bus keepers are still activated as long as xmbk is one. ? bit 6:3 ? res: reserved bits these bits are reserved and will always read as zero. w hen writing to this address location, write these bits to zero for compatibility with future devices. ? bit 2:0 ? xmm2, xmm1, xmm0: external memory high mask w hen the external memory is enabled, all port c pi ns are default used for the high address byte. if the full 60kbytes address space is not required to access the external memory, some, or all, port c pins can be released for normal port pin function as described in table 9-4 . as described in ?using all 64kbytes locations of external memory? on page 33 , it is possible to use the xmmn bits to access all 64kbytes locations of the external memory. table 9-4. port c pins released as n ormal port pins when the external memory is enabled xmm2 xmm1 xmm0 # bits for external memory address released port pins 0 0 0 8 (full 56kbytes space) n one 001 7 pc7 010 6 pc7 - pc6 011 5 pc7 - pc5 100 4 pc7 - pc4 101 3 pc7 - pc3 110 2 pc7 - pc2 111 n o address high bits full port c
40 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10. system clock and clock options this section describes the clock options for the avr microcontroller. 10.1 overview figure 10-1 presents the principal clock systems in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ?power management and sleep modes? on page 52 . the clock systems are detailed below. figure 10-1. clock distribution. 10.2 clock systems and their distribution 10.2.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. examples of such modules are the general pur pose register file, the status register and the data memory holding the stack pointer. halting the cpu clock inhibits the core from performing general operations and calculations. general i/o modules asynchronous timer/counter cpu core ram clk i/o clk a s y avr clock control unit clk cpu flash and eeprom clk fla s h s ource clock watchdog timer watchdog oscillator reset logic clock multiplexer watchdog clock calibrated rc oscillator timer/counter oscillator crystal oscillator low-frequency crystal oscillator external clock adc clk adc s ystem clock prescaler
41 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10.2.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, spi, and usart. the i/o clock is also used by the external inte rrupt module, but note that some external inter- rupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also note that start condition detection in the usi module is carried out asynchro- nously when clk i/o is halted, t w i address recognition in all sleep modes. 10.2.3 flash clock ? clk flash the flash clock controls operation of the flash in terface. the flash clock is usually active simul- taneously with the cpu clock. 10.2.4 asynchronous timer clock ? clk asy the asynchronous timer clock al lows the asynchronous timer/c ounter to be clocked directly from an external clock or an external 32khz clock crystal. the dedicated clock domain allows using this timer/counter as a real-time counter even when the device is in sleep mode. 10.2.5 adc clock ? clk adc the adc is provided with a dedicated clock domain. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this gives more accurate adc conversion results. 10.3 clock sources the device has the following clock source options, selectable by flash fuse bits as shown below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. n ote: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. table 10-1. device clocking options select (1) device clocking option cksel3:0 low power crystal oscillator 1111 - 1000 full swing crystal oscillator 0111 - 0110 low frequency crystal oscillator 0101 - 0100 internal 128khz rc oscillator 0011 calibrated internal rc oscillator 0010 external clock 0000 reserved 0001
42 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10.3.1 default clock source the device is shipped with inte rnal rc oscillator at 8.0mhz a nd with the fuse ckdiv8 pro- grammed, resulting in 1.0mhz system clock. th e startup time is set to maximum and time-out period enabled. (cksel = "0010", su t = "10", ckdiv8 = "0"). th e default setti ng ensures that all users can make their desired clock source se tting using any available programming interface. 10.3.2 clock start-up sequence any clock source needs a sufficient v cc to start oscillating and a minimum number of oscillating cycles before it can be considered stable. to ensure sufficient v cc , the device issues an internal reset with a time-out delay (t tout ) after the device reset is released by all other reset sources. ?on-chip debug system? on page 55 describes the start conditions for the internal reset. the delay (t tout ) is timed from the w atchdog oscillator and the number of cycles in the delay is set by the sutx and ckselx fuse bits. the selectable delays are shown in table 10-2 . the frequency of the w atchdog oscillator is voltage dependent as shown in ?typical characteristics? on page 385 . main purpose of the delay is to keep the avr in reset until it is supplied with minimum v cc . the delay will not monitor t he actual voltage and it w ill be required to select a delay longer than the vcc rise time. if this is not possible, an intern al or external brown-out detection circuit should be used. a bod circuit will ensure sufficient v cc before it releases the reset, and the time-out delay can be disabled. disabling the time-out delay wi thout utilizing a brown-out detection circuit is not recommended. the oscillator is required to oscillate for a minimu m number of cycles befo re the clock is consid- ered stable. an inte rnal ripple counter monito rs the oscillator output cl ock, and keep s the internal reset active for a given number of clock cycl es. the reset is then released and the device will start to execute. the recommend ed oscillator start-up time is dependent on the clock type, and varies from 6 cycles for an externally applied clock to 32k cycles for a low frequency crystal. the start-up sequence for the clock includes both the time-out delay and the start-up time when the device starts up from reset. w hen starting up from power-save or power-down mode, v cc is assumed to be at a sufficient level and only the start-up time is included. 10.4 low power crystal oscillator pins xtal1 and xtal2 are input and output, respec tively, of an invertin g amplifier which can be configured for use as an on-c hip oscillator, as shown in figure 10-2 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a low power oscillator, with reduced voltage swing on the xtal2 out- put. it gives the lowest power consumption, but is not capable of driving other clock inputs, and may be more susceptible to noise in noisy environments. in these cases, refer to the ?full swing crystal oscillator? on page 44 . table 10-2. n umber of w atchdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 0ms 0ms 0 4.1ms 4.3ms 512 65ms 69ms 8k (8,192)
43 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 10-3 . for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 10-2. crystal oscillator connections the low power oscillator c an operate in three diff erent modes, each optimi zed for a specific fre- quency range. the operating mode is select ed by the fuses cksel3:1 as shown in table 10-3 . n otes: 1. this is the recommended cksel sett ings for the different frequency ranges. 2. this option should not be used with crystals, only with ceramic resonators. 3. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets th e frequency specification of the device. 4. maximum frequency when using ceramic oscillator is 10mhz. the cksel0 fuse together with the sut1:0 fuses select the start-up times as shown in table 10-4 . table 10-3. low power crystal osc illator operating modes (3) frequency range (mhz) cksel3:1 (1) recommended range for capacitors c1 and c2 (pf) 0.4 - 0.9 100 (2) ? 0.9 - 3.0 101 12 - 22 3.0 - 8.0 110 12 - 22 8.0 - 16.0 (4) 111 12 - 22 table 10-4. start-up times for the low power cr ystal oscillator clock selection oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1:0 ceramic resonator, fast rising power 258 ck 14ck + 4.1ms (1) 000 ceramic resonator, slowly rising power 258 ck 14ck + 65ms (1) 001 ceramic resonator, bod enabled 1k ck 14ck (2) 010 xtal2 xtal1 gnd c2 c1
44 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. these options should only be used when no t operating close to the maximum frequency of the device, and only if frequency stability at start- up is not important for the application. these options are not suitable for crystals. 2. these options are intended for use with cerami c resonators and will ensure frequency stability at start-up. they can also be used with crystal s when not operating close to the maximum fre- quency of the device, and if frequency stability at start-up is not important for the application. 10.5 full swing crystal oscillator pins xtal1 and xtal2 are input and output, respec tively, of an invertin g amplifier which can be configured for use as an on-chip oscillator, as shown in figure 10-2 on page 43 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a full s wing oscillator, wit h rail-to-rail swing on th e xtal2 output. this is useful for driving other clock inputs and in noisy environments. the current consumption is higher than the ?low power crystal os cillator? on page 42 . n ote that the full swing crystal oscillator will only operate for v cc = 2.7 - 5.5 volts. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 10-6 on page 45 . for ceramic resonato rs, the capacitor val- ues given by the manufacturer should be used. the operating mode is selected by the fuses cksel3:1 as shown in table 10-5 . n ote: 1. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets th e frequency specification of the device. ceramic resonator, fast rising power 1k ck 14ck + 4.1ms (2) 011 ceramic resonator, slowly rising power 1k ck 14ck + 65ms (2) 100 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65ms 1 11 table 10-4. start-up times for the low power crysta l oscillator clock se lection (continued) oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1:0 table 10-5. full swing crystal osc illator operating modes (1) frequency range (mhz) cksel3:1 recommended range for capacitors c1 and c2 (pf) 0.4 - 16 011 12 - 22
45 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. these options should only be used when no t operating close to the maximum frequency of the device, and only if frequency stability at start- up is not important for the application. these options are not suitable for crystals. 2. these options are intended for use with cerami c resonators and will ensure frequency stability at start-up. they can also be used with crystal s when not operating close to the maximum fre- quency of the device, and if frequency stability at start-up is not important for the application. 10.6 low frequency crystal oscillator the device can utilize a 32.768khz watch crystal as clock source by a dedicated low frequency crystal oscillator. the crystal should be connected as shown in figure 10-3 on page 46 . w hen this oscillator is selected, start-up times are determined by the sut fuses and cksel0 as shown in table 10-8 on page 46 . the low-frequency crystal oscillator provi des an internal load capacitance, see table 10-7 at each xtal/tosc pin. table 10-6. start-up times for the full swing crystal oscillator clock selection oscillator source / power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1:0 ceramic resonator, fast rising power 258 ck 14ck + 4.1ms (1) 000 ceramic resonator, slowly rising power 258 ck 14ck + 65ms (1) 001 ceramic resonator, bod enabled 1k ck 14ck (2) 010 ceramic resonator, fast rising power 1k ck 14ck + 4.1ms (2) 011 ceramic resonator, slowly rising power 1k ck 14ck + 65ms (2) 100 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65ms 1 11 table 10-7. capacitance for low frequency oscillator device 32khz oscillator cap (xtal1/tosc1) cap (xtal2/tosc2) atmega640/1280/1281/2560/2561 system osc. 18pf 8pf timer osc. 6pf 6pf
46 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the capacitance (ce + ci) needed at each xtal/tosc pin can be calculated by using: where: ce - is optional external capacitors as described in figure 10-3 on page 46 . ci - is the pin capacitance in table 10-7 on page 45 . cl - is the load capacitance for a 32.768khz crystal specified by the crystal vendor. c s - is the total stray capacitance for one xtal/tosc pin. crystals specifying load capacitance (cl) higher than the ones given in the table 10-7 on page 45 , require external capacitors applied as described in figure 10-3 on page 46 . figure 10-3. crystal oscillator connections to find suitable load capacitance for a 32.768khz crysal, please consult the crystal datasheet. w hen this oscillator is selected, start-up ti mes are determined by the sut fuses and cksel0 as shown in table 10-8 . n ote: 1. these options should only be used if frequen cy stability at start-up is not important for the application. table 10-8. start-up times for the low frequency crystal oscillator clock selection power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1:0 bod enabled 1k ck 14ck (1) 000 fast rising power 1k ck 14ck + 4.1ms (1) 001 slowly rising power 1k ck 14ck + 65ms (1) 010 reserved 0 11 bod enabled 32k ck 14ck 1 00 fast rising power 32k ck 14ck + 4.1ms 1 01 slowly rising power 32k ck 14ck + 65ms 1 10 reserved 1 11 ce ci + 2 cl ? c s ? = c e c i c e c i c s c s tosc2 tosc1 x1
47 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10.7 calibrated internal rc oscillator by default, the internal rc osc illator provides an a pproximate 8mhz clock. though voltage and temperature dependent, this clock can be very accurately calibrated by the user. see table 31-1 on page 371 and ?internal oscillator sp eed? on page 404 for more details. the device is shipped with the ckdiv8 fuse programmed. see ?system clock presca ler? on page 49 for more details. this clock may be selected as the system clock by programming the cksel fuses as shown in table 10-9 . if selected, it will operate with no external components. during re set, hardware loads the pre-programmed calibration value into the osccal register and thereby automatically cal- ibrates the rc oscillator. the accuracy of this calibration is shown as factory calibration in table 31-1 on page 371 . by changing the osccal register from s w , see ?osccal ? oscillator ca libration register? on page 50 , it is possible to get a higher calibration accuracy than by using the factory calibration. the accuracy of this calibration is shown as user calibration in table 31-1 on page 371 . w hen this oscillator is used as the chip clock, the w atchdog oscillator will still be used for the w atchdog timer and for the reset time-out. for more information on the pre-programmed cali- bration value, see the section ?calibration byte? on page 338 . n otes: 1. the device is shipped with this option selected. 2. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be programmed in order to divide the internal frequency by 8. w hen this oscillator is selected, start-up times are determined by the sut fuses as shown in table 10-10 . n ote: 1. the device is shipped with this option selected. 10.8 128 khz internal oscillator the 128khz internal oscillator is a low power oscillator providing a clock of 128khz. the fre- quency is nominal at 3v and 25 c. this clock may be select as the system clock by programming the c ksel fuses to ?11? as shown in table 10-11 . n ote: 1. n ote that the 128khz oscillator is a very low power clock source, and is not designed for high accuracy. table 10-9. internal calibrated rc o scillator operating modes (1)(2) frequency range (mhz) cksel3:0 7.3 - 8.1 0010 table 10-10. start-up times for the internal calib rated rc oscillator clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1:0 bod enabled 6ck 14ck 00 fast rising power 6ck 14ck + 4.1ms 01 slowly rising power 6ck 14ck + 65ms (1) 10 reserved 11 table 10-11. 128khz internal osc illator operating modes (1) nominal frequency cksel3:0 128khz 0011
48 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w hen this clock source is selected, start-up ti mes are determined by the sut fuses as shown in table 10-12 . 10.9 external clock to drive the device from an external clock source, xtal1 should be driven as shown in figure 10-4 . to run the device on an external clock, the cksel fuses must be programmed to ?0000?. figure 10-4. external clock drive configuration w hen this clock source is selected, start-up ti mes are determined by the sut fuses as shown in table 10-15 on page 51 . w hen applying an external clock, it is required to avoid sudden changes in the applied clock fre- quency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredict able behavior. if changes of more than 2% is required, ensure that the mcu is kept in reset during the changes. table 10-12. start-up times for the 128k hz internal oscillator power conditions start-up time from power- down and power-save additional delay from reset sut1:0 bod enabled 6ck 14ck 00 fast rising power 6ck 14ck + 4ms 01 slowly rising power 6ck 14ck + 64ms 10 reserved 11 table 10-13. crystal oscillator clock frequency nominal frequency cksel3:0 0 - 16mhz 0000 table 10-14. start-up times for the external clock selection power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) sut1:0 bod enabled 6ck 14ck 00 fast rising power 6ck 14ck + 4.1ms 01 slowly rising power 6ck 14ck + 65ms 10 reserved 11 nc external clock s ignal xtal2 xtal1 gnd
49 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote that the system clock prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation. refer to ?system clock prescaler? for details. 10.10 clock output buffer the device can output the system clock on t he clko pin. to enable the output, the ckout fuse has to be programmed. this mode is suitable when the chip clock is used to drive other cir- cuits on the system. the clock also will be output during reset, and the normal operation of i/o pin will be overridden when the fu se is programmed. an y clock source, includi ng the internal rc oscillator, can be selected when the clock is out put on clko. if the system clock prescaler is used, it is the divided system clock that is output. 10.11 timer/counter oscillator the device can operate its timer/counter2 from an external 32.768khz watch crystal or a exter- nal clock source. see figure 10-2 on page 43 for crystal connection. applying an external clock source to tosc1 r equires exclk in the assr register written to logic one. see ?asynchronous operation of timer/counter2? on page 184 for further description on selecting external clock as input instead of a 32khz crystal. 10.12 system clock prescaler the atmega640/1280/1281/2560/2561 has a system clock prescaler, and the system clock can be divided by setting the ?clkpr ? clock prescale register? on page 50 . this feature can be used to decrease the system clock frequency and the power consumption when the requirement for processing power is low. this can be used with all clock sour ce options, and it will affect the clock frequency of the cpu and all synchronous peripherals. clk i/o , clk adc , clk cpu , and clk flash are divided by a factor as shown in table 10-15 on page 51 . w hen switching between prescaler settings, the system clock prescaler ensures that no glitches occurs in the clock system. it also ensures that no intermediate frequency is higher than neither the clock frequency corresponding to the previous setting, nor the clock frequency corre- sponding to the new setting. the ripple counter that implements the prescaler runs at the frequency of the undivided clock, which may be faster than the cpu's clock frequency. hence, it is not possible to determine the state of the prescaler - even if it were readable, and the exact time it takes to switch from one clock division to the other cann ot be exactly predicted. from th e time the clkps values are writ- ten, it takes between t1 + t2 and t1 + 2 t2 before the new clock frequency is active. in this interval, 2 active clock edges are produced. here, t1 is the previous clock period, and t2 is the period corresponding to the new prescaler setting. to avoid unintentional changes of clock frequency, a special write procedure must be followed to change the clkps bits: w rite the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. w ithin four cycles, write th e desired value to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted.
50 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10.13 register description 10.13.1 osccal ? oscillato r calibration register ? bits 7:0 ? cal7:0: oscillator calibration value the oscillator calibration register is used to trim the calibrated internal rc oscillator to remove process variations from the oscillator frequency. a pre-programmed calibration value is automatically written to this register during chip reset, giving the factory calibrated frequency as specified in table 31-1 on page 371 . the application software can write this register to change the oscillator frequency. the os cillator can be calibrated to frequencies as specified in table 31- 1 on page 371 . calibration outside that range is not guaranteed. n ote that this oscillator is us ed to time eeprom and flash write accesses, and these write times will be affected accordingly. if the eeprom or flash are writ ten, do not calibrate to more than 8.8 mhz. other wise, the eeprom or flash write may fail. the cal7 bit determines the range of operation for the oscillator. setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. the two fre- quency ranges are overlapping, in other words a setting of osccal = 0x7f gives a higher frequency than osccal = 0x80. the cal6..0 bits are used to tune the frequency within the selected range. a setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7f gives the highest frequency in the range. 10.13.2 clkpr ? clock prescale register ? bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enab le change of the clkps bits. the clkpce bit is only updated when the other bits in cl kpr are simultaneously wr itten to zero. clkpce is cleared by hardware four cycles af ter it is written or when clkps bits are written. rewriting the clkpce bit within this time-out period does neither extend the time-out period, nor clear the clkpce bit. ? bits 3:0 ? clkps3:0: clock prescaler select bits 3 - 0 these bits define the division factor between the selected clock source and the internal system clock. these bits can be written run-time to vary the clock frequency to suit the application requirements. as the divider divides the master clock input to the mcu, the speed of all synchro- nous peripherals is reduced when a division fact or is used. the division factors are given in table 10-15 on page 51 . the ckdiv8 fuse determines the initial value of the clkps bits. if ckdiv8 is unprogrammed, the clkps bits will be reset to ?0000?. if ckdiv8 is programmed, clkps bits are reset to ?0011?, giving a division factor of 8 at start up. this feature should be used if the selected clock bit 76543210 (0x66) cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value device spec ific calibration value bit 76543210 (0x61) clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/ w rite r/ w rrrr/ w r/ w r/ w r/ w initial value 0 0 0 0 see bit description
51 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 source has a higher frequency than the maximum frequency of the device at the present operat- ing conditions. n ote that any value can be written to the clkps bits regardless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is chosen if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. the device is shipped with the ckdiv8 fuse programmed. table 10-15. clock prescaler select clkps3 clkps2 clkps1 clkps0 clock division factor 0000 1 0001 2 0010 4 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 1001 reserved 1010 reserved 1011 reserved 1100 reserved 1101 reserved 1110 reserved 1111 reserved
52 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 11. power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consump- tion to the application?s requirements. 11.1 sleep modes figure 10-1 on page 40 presents the different clock systems in the atmega640/1280/1281/2560/2561, and their distribution. the figure is helpful in selecting an appropriate sleep mode. table 11-1 shows the different sleep modes and their wake-up sources. n otes: 1. only recommended with external crystal or resonator selected as clock source. 2. if timer/counter2 is running in asynchronous mode. 3. for i n t7:4, only level interrupt. to enter any of the sleep modes, the se bit in ?smcr ? sleep mode control register? on page 56 must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the smcr register select which sleep mode will be ac tivated by the sleep instruc- tion. see table 11-2 on page 56 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the st art-up time, executes the interrupt routine, and resumes execution from the instruction followi ng sleep. the contents of the register file and sram are unaltered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. 11.2 idle mode w hen the sm2:0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing the spi, usart, analog comparator, adc, 2-wire serial inter- face, timer/counters, w atchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the ot her clocks to run. table 11-1. active clock domains and w ake-up sources in the different sleep modes. active clock domains oscillators wake-up sources sleep mode clk cpu clk flash clk io clk adc clk asy main clock source enabled timer osc enabled int7:0 and pin change twi address match timer2 spm/ eeprom ready adc wdt interrupt other i/o idle x x x x x (2) xxxxxxx adc n rm x x x x (2) x (3) xx (2) xxx power-down x (3) xx power-save x x (2) x (3) xx x standby (1) xx (3) xx extended standby x (2) xx (2) x (3) xx x
53 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the timer overflow and usart transmit complete interrupts. if wake-up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the acd bit in the analog comparator control and status regist er ? acsr. this will reduce power consumption in idle mode. if t he adc is enabled, a conversion starts automati- cally when this mode is entered. 11.3 adc noise reduction mode w hen the sm2:0 bits are written to 001, th e sleep instruction makes the mcu enter adc n oise reduction mode, stopping the cpu but allowi ng the adc, the external interrupts, 2-wire serial interface address match, timer/counter2 and the w atchdog to continue operating (if enabled). this sleep mode basically halts clki /o, clkcpu, and clkflash, while allowing the other clocks to run. this improves the noise environment for the ad c, enabling higher resolution measurements. if the adc is enabled, a conversion starts automatically when this mode is entered. apart form the adc conversion complete interru pt, only an external reset, a w atchdog system reset, a w atchdog interrupt, a brown-out reset, a 2-wire serial interface interrupt, a timer/counter2 interrupt, an spm/eeprom ready interrupt, an external level interrupt on i n t7:4 or a pin change interrupt can wakeup the mcu from adc n oise reduction mode. 11.4 power-down mode w hen the sm2:0 bits are written to 010, the sleep instruction makes the mcu enter power- down mode. in this mode, the external osc illator is stopped, while the external interrupts, the 2- wire serial interface, and the w atchdog continue operating (if enabled). only an external reset, a w atchdog reset, a brown-out reset, 2-wire serial interface address match, an external level interrupt on i n t7:4, an external interrupt on i n t3:0, or a pin change interrupt can wake up the mcu. this sleep mode basically halts all gener ated clocks, allowing operation of asynchronous modules only. n ote that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external interrupts? on page 112 for details. w hen waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 41 . 11.5 power-save mode w hen the sm2:0 bits are written to 011, the sleep instruction makes the mcu enter power- save mode. this mode is identical to power-down, with one exception: if timer/counter2 is e nabled, it will keep running during sleep. the device can wake up from either timer overflow or output compare event from timer/counter2 if the corresponding timer/counter2 interrupt enable bits are set in timsk2, and the global interrupt enable bit in sreg is set. if timer/counter2 is not running, power-down mode is recommended instead of power-save mode. the timer/counter2 can be clocked both synchronously and asynchronously in power-save mode. if the time r/counter2 is not using t he asynchronous clock, the timer/counter oscillator is
54 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 stopped during sleep. if the timer/counter2 is not using the synchronous clock, the clock source is stopped during sleep. n ote that even if the synchronous clock is running in power-save, this clock is only available for the timer/counter2. 11.6 standby mode w hen the sm2:0 bits are 110 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. fr om standby mode, the device wakes up in six clock cycles. 11.7 extended standby mode w hen the sm2:0 bits are 111 and an external crystal/resonator clock option is selected, the sleep instruction makes the m cu enter extended standby mode . this mode is identical to power-save mode with th e exception that the oscillator is kept running. from extended standby mode, the device wakes up in six clock cycles. 11.8 power reduction register the power reduction register (prr), see ?prr0 ? power reduction register 0? on page 56 and ?prr1 ? power reduction register 1? on page 57 , provides a method for stopping the clock to individual peripherals to reduce power consumption. n ote that when the clock for a peripheral is stopped, then: ? the current state of the peripheral is frozen ? the associated registers can not be read or written ? resources used by the peripherals (for example i/o pin, etc.) will remain occupied the peripheral should in most cases be disabled before stopping the clock. w aking up a mod- ule, which is done by cleaning the bit in prr, puts the module in the same state as before shutdown. module shutdown can be used in idle mode or active mode to significantly reduce the overall power consumption. see ?power-down supply current? on page 392 for examples. in all other sleep modes, the clock is already stopped. 11.9 minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possi ble of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consideration when trying to achieve th e lowest possible power consumption. 11.9.1 analog to digital converter if enabled, the adc will be enabled in all sleep modes. to save power, the adc should be dis- abled before entering any sleep mode. w hen the adc is turned off and on again, the next conversion will be an extended conversion. refer to ?adc ? analog to digital converter? on page 275 for details on adc operation. 11.9.2 analog comparator w hen entering idle mode, the analog comparator should be disabled if not used. w hen entering adc n oise reduction mode, the analog comparator should be disabled. in other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up
55 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 to use the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. otherwise, the internal voltage reference will be enabled, independent of sleep mode. refer to ?ac ? analog comparator? on page 271 for details on how to configure the ana- log comparator. 11.9.3 brown-out detector if the brown-out detector is not needed by the application, this module should be turned off. if the brown-out detector is enabled by the bo dlevel fuses, it will be enabled in all sleep modes, and hence, always co nsume power. in the deeper sleep modes, this w ill contribute sig- nificantly to the total current consumption. refer to ?brown-out detect ion? on page 61 for details on how to configure the brown-out detector. 11.9.4 internal voltage reference the internal voltage referenc e will be enabled when needed by the brown-out de tection, the analog comparator or the adc. if these modules are disabled as described in the sections above, the internal voltage re ference will be disabled and it will not be consuming power. w hen turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal volt- age reference? on page 62 for details on the start-up time. 11.9.5 watchdog timer if the w atchdog timer is not needed in the application, the module should be turned off. if the w atchdog timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. in the deeper slee p modes, this will contribute signific antly to the total current consump- tion. refer to ?interrupts? on page 105 for details on how to configure the w atchdog timer. 11.9.6 port pins w hen entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buf fers of the device will be disabled. this ensures that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for detec ting wake-up conditions, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 74 for details on which pins are enabled. if the input buffer is enabl ed and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to v cc /2 on an input pin can cause significant current even in active mode. digital input buffers can be disabled by writing to the digital input disable registers (didr2, didr1 and didr0). refer to ?didr2 ? digital input disable register 2? on page 295 , ?didr1 ? digital input disable register 1? on page 274 and ?didr0 ? digital input disable register 0? on page 295 for details. 11.9.7 on-chip debug system if the on-chip debug system is enabled by the ocde n fuse and the chip enters sleep mode, the main clock source is enabled, and hence , always consumes power. in the deeper sleep modes, this will contribute significantly to the total cu rrent consumption.
56 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 there are three alte rnative ways to disable the ocd system: ? disable the ocde n fuse ? disable the jtage n fuse ? w rite one to the jtd bit in mcucr 11.10 register description 11.10.1 smcr ? sleep mode control register the sleep mode control register contains control bits for power management. ? bits 3, 2, 1 ? sm2:0: sleep mode select bits 2, 1, and 0 these bits select between the five available sleep modes as shown in table 11-2 . n ote: 1. standby modes are only recommended for use with external crystals or resonators. ? bit 1 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu enteri ng the sleep mode unless it is the programmer?s purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instruction and to clear it immediately af ter waking up. 11.10.2 prr0 ? power reduction register 0 ? bit 7 - prtwi: power reduction twi w riting a logic one to this bit shuts down the t w i by stopping the clock to the module. w hen waking up the t w i again, the t w i should be re initialized to ensure proper operation. bit 76543210 0x33 (0x53) ????sm2sm1sm0sesmcr read/ w rite rrrrr/ w r/ w r/ w r/ w initial value00000000 table 11-2. sleep mode select sm2 sm1 sm0 sleep mode 000 idle 001 adc n oise reduction 010 power-down 011 power-save 100 reserved 101 reserved 1 1 0 standby (1) 1 1 1 extended standby (1) bit 7 6 543 2 1 0 (0x64) prtwi prtim2 prtim0 ? prtim1 prspi prusart0 pradc prr0 read/ w rite r/ w r/ w r/ w rr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
57 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 - prtim2: power reduction timer/counter2 w riting a logic one to this bit shuts down the timer/counter2 module in synchronous mode (as2 is 0). w hen the timer/counter2 is en abled, operation will continue like before the shutdown. ? bit 5 - prtim0: power reduction timer/counter0 w riting a logic one to this bit shuts down the timer/counter0 module. w hen the timer/counter0 is enabled, operation will cont inue like before the shutdown. ? bit 4 - res: reserved bit this bit is reserved bit and will always read as zero. ? bit 3 - prtim1: power reduction timer/counter1 w riting a logic one to this bit shuts down the timer/counter1 module. w hen the timer/counter1 is enabled, operation will cont inue like before the shutdown. ? bit 2 - prspi: power reduction serial peripheral interface w riting a logic one to this bit shuts down the seri al peripheral interface by stopping the clock to the module. w hen waking up the spi again, the spi should be re initialized to ensure proper operation. ? bit 1 - prusart0: power reduction usart0 w riting a logic one to this bit shuts down the u sart0 by stopping the clock to the module. w hen waking up the usart0 again, the usart0 should be re initialized to ensure proper operation. ? bit 0 - pradc: power reduction adc w riting a logic one to this bit shuts down the adc. the adc must be disabled before shut down. the analog comparator cannot use the adc input mux when the adc is shut down. 11.10.3 prr1 ? power reduction register 1 ? bit 7:6 - res: reserved bits these bits are reserved and will always read as zero. ? bit 5 - prtim5: power reduction timer/counter5 w riting a logic one to this bit shuts down the timer/counter5 module. w hen the timer/counter5 is enabled, operation will cont inue like before the shutdown. ? bit 4 - prtim4: power reduction timer/counter4 w riting a logic one to this bit shuts down the timer/counter4 module. w hen the timer/counter4 is enabled, operation will cont inue like before the shutdown. ? bit 3 - prtim3: power reduction timer/counter3 w riting a logic one to this bit shuts down the timer/counter3 module. w hen the timer/counter3 is enabled, operation will cont inue like before the shutdown. bit 76543 2 1 0 (0x65) ? ? prtim5 prtim4 prtim3 prusart3 prusart2 prusart1 prr1 read/ w rite r r r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
58 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 2 - prusart3: power reduction usart3 w riting a logic one to this bit shuts down the u sart3 by stopping the clock to the module. w hen waking up the usart3 again, the usart3 should be re initialized to ensure proper operation. ? bit 1 - prusart2: power reduction usart2 w riting a logic one to this bit shuts down the u sart2 by stopping the clock to the module. w hen waking up the usart2 again, the usart2 should be re initialized to ensure proper operation. ? bit 0 - prusart1: power reduction usart1 w riting a logic one to this bit shuts down the u sart1 by stopping the clock to the module. w hen waking up the usart1 again, the usart1 should be re initialized to ensure proper operation.
59 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 12. system control and reset 12.1 resetting the avr during reset, all i/o registers are set to their initial values, and the program starts execution from the reset vector. the instruction placed at the reset vector must be a jmp ? absolute jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the app lication section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 12-1 on page 60 shows the reset logic. ?system and reset characte ristics? on page 372 defines the electrical parameters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the user through the sut and cksel fuses. the dif- ferent selections for the delay period are presented in ?clock sources? on page 41 . 12.2 reset sources the atmega640/1280/1281/2560/2561 has five sources of reset: ? power-on reset . the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ) ? external reset . the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length ? watchdog reset . the mcu is reset when the w atchdog timer period expires and the w atchdog is enabled ? brown-out reset . the mcu is reset when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled ? jtag avr reset . the mcu is reset as long as there is a logic one in the reset register, one of the scan chains of the jtag system. refer to the section ?ieee 1149.1 (jtag) boundary-scan? on page 302 for details
60 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 12-1. reset logic 12.2.1 power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detection level is defined in ?system and reset characteristics? on page 372 . the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a fa ilure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after v cc rise. the reset signal is acti vated again, without any delay, when v cc decreases below the detection level. figure 12-2. mcu start-up, reset tied to v cc mcu s tatus register (mcu s r) brown-out reset circuit bodlevel [2..0] delay counters ck s el[3:0] ck timeout wdrf borf extrf porf data b u s clock generator s pike filter pull-up resistor jtrf jtag reset register watchdog oscillator s ut[1:0] power-on reset circuit v re s et time-out internal re s et t tout v pot v r s t cc
61 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 12-3. mcu start-up, reset extended externally 12.2.2 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see ?system and reset characteristics? on page 372 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. w hen the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter starts the mcu after the time-out period ? t tout ? has expired. figure 12-4. external reset during operation 12.2.3 brown-out detection atmega640/1280/1281/2560/2561 has an on-chip brown-out detection (bod) circuit for moni- toring the v cc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the bodlevel fu ses. the trigger level ha s a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. w hen the bod is enabled, and v cc decreases to a value below the trigger level (v bot- in figure 12-5 on page 62 ), the brown-out reset is immediately activated. w hen v cc increases above the trigger level (v bot+ in figure 12-5 on page 62 ), the delay counter starts the mcu after the time- out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for lon- ger than t bod given in ?system and reset characteristics? on page 372 . re s et time-out internal re s et t tout v pot v r s t v cc cc
62 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 12-5. brown-out reset during operation 12.2.4 watchdog reset w hen the w atchdog times out, it will gene rate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . see ? w atchdog timer? on page 55. for details on operation of the w atchdog timer. figure 12-6. w atchdog reset during operation 12.3 internal voltage reference atmega640/1280/1281/2560/2561 features an internal bandgap reference. this reference is used for brown-out detection, and it can be used as an input to the analog comparator or the adc. 12.3.1 voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in ?system and reset characteristics? on page 372 . to save power, the reference is not always turned on. the reference is on during the following situations: 1. w hen the bod is enabled (by prog ramming the bodlevel [2:0] fuse). 2. w hen the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). 3. w hen the adc is enabled. thus, when the bod is not enabled, after setting the acbg bit or enabling the adc, the user must always allow the reference to start up before the output from the analog comparator or v cc re s et time-out internal re s et v bot- v bot+ t tout ck cc
63 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 adc is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode. 12.4 watchdog timer 12.4.1 features ? clocked from separate on-chip oscillator ? 3 operating modes ? interrupt ? system reset ? interrupt and system reset ? selectable time-out pe riod from 16ms to 8s ? possible hardware fuse watchdog al ways on (wdton) for fail-safe mode figure 12-7. w atchdog timer 12.4.2 overview atmega640/1280/1281/2560/2561 has an enhanced w atchdog timer ( w dt). the w dt is a timer counting cycles of a separate on-chip 128khz oscillator. the w dt gives an interrupt or a system reset when the counter reaches a given time -out value. in normal operation mode, it is required that the system uses the w dr - w atchdog timer reset - instruction to restart the coun- ter before the time-out value is reached. if the system doesn't restart the counter, an interrupt or system reset will be issued. in interrupt mode, the w dt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. in system reset mode, the w dt gives a reset when the timer expires. this is typically used to prevent sys tem hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an inter- rupt and then switch to system reset mode. this mode will for instance allow a safe shutdown by saving critical parameters before a system reset. the w atchdog always on ( w dto n ) fuse, if programmed, will force the w atchdog timer to sys- tem reset mode. w ith the fuse programmed the system reset mode bit ( w de) and interrupt mode bit ( w die) are locked to 1 and 0 respectively. to further ensure program security, altera- 128 khz oscillator osc/2k osc/4k osc/8k osc/16k osc/32k osc/64k osc/128k osc/256k osc/512k osc/1024k wdp0 wdp1 wdp2 wdp3 watchdog reset wde wdif wdie mcu reset interrupt
64 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 tions to the w atchdog set-up must follow timed sequences. the sequence for clearing w de and changing time-out configuration is as follows: 1. in the same operation, write a logic one to the w atchdog change enable bit ( w dce) and w de. a logic one must be written to w de regardless of the previous value of the w de bit. 2. w ithin the next four clock cycles, write the w de and w atchdog prescaler bits ( w dp) as desired, but with the w dce bit cleared. this must be done in one operation. the following code example shows one assembly and one c function for turning off the w atch- dog timer. the example assumes that interrupt s are controlled (for example by disabling interrupts globally) so that no interrupts will occur during the execution of these functions.
65 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. the example code assumes that the pa rt specific header file is included. 2. if the w atchdog is accidentally enabled, for exampl e by a runaway pointer or brown-out condi- tion, the device will be reset and the w atchdog timer will stay enabled. if the code is not set up to handle the w atchdog, this might lead to an eternal lo op of time-out resets . to avoid this sit- uation, the application software should always clear the w atchdog system reset flag ( w drf) and the w de control bit in the initialisation routine, even if the w atchdog is not in use. the following code example shows one assembly and one c function for changing the time-out value of the w atchdog timer. assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 66 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. the example code assumes that the pa rt specific header file is included. 2. the w atchdog timer should be reset before any change of the w dp bits, since a change in the w dp bits can result in a time-out when switching to a shorter time-out period. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence in r16, wdtcsr ori r16, (1< 67 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 12.5 register description 12.5.1 mcusr ? mcu status register the mcu status register provides information on which reset source caused an mcu reset. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a w atchdog reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bi t is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 12.5.2 wdtcsr ? watchdog timer control register ? bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs in the w atchdog timer and the w atchdog timer is config- ured for interrupt. w dif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, w dif is cleared by writing a logic one to the flag. w hen the i-bit in sreg and w die are set, the w atchdog time-out interrupt is executed. bit 76543210 0x35 (0x55) ? ? ? jtrf wdrf borf extrf porf mcusr read/ w rite r r r r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 see bit description bit 76543210 (0x60) wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcsr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 x 0 0 0
68 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 - wdie: watchdog interrupt enable w hen this bit is written to one and the i-bit in the status register is set, the w atchdog interrupt is enabled. if w de is cleared in combination with this setting, the w atchdog timer is in interrupt mode, and the corresponding interrupt is executed if time-out in the w atchdog timer occurs. if w de is set, the w atchdog timer is in interrupt and syst em reset mode. the first time-out in the w atchdog timer will set w dif. executing the corresponding interr upt vector will clear w die and w dif automatically by hardware (the w atchdog goes to system reset mode). this is use- ful for keeping the w atchdog timer security while using the interrupt. to stay in interrupt and system reset mode, w die must be set after each interrupt. this should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the w atchdog system reset mode. if the interrupt is not executed before the next time-out, a sys- tem reset will be applied. n ote: 1. w dto n fuse set to ?0? means programmed and ?1? means unprogrammed. ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changing w de and prescaler bits. to clear the w de bit, and/or change the prescaler bits, w dce must be set. once written to one, hardware will clear w dce after four clock cycles. ? bit 3 - wde: watchdog system reset enable w de is overridden by w drf in mcusr. this means that w de is always set when w drf is set. to clear w de, w drf must be cleared first. this feature ensures multiple resets during con- ditions causing failure, and a safe start-up after the failure. ? bit 5, 2:0 - wdp3:0: watchdog timer prescaler 3, 2, 1 and 0 the w dp3:0 bits determine the w atchdog timer prescaling when the w atchdog timer is run- ning. the different prescaling values and thei r corresponding time-out periods are shown in table 12-2 on page 69 . table 12-1. w atchdog timer configuration wdton (1) wde wdie mode action on time-out 1 0 0 stopped n one 1 0 1 interrupt mode interrupt 1 1 0 system reset mode reset 111 interrupt and system reset mode interrupt, then go to system reset mode 0 x x system reset mode reset
69 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 . table 12-2. w atchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 16ms 0 0 0 1 4k (4096) cycles 32ms 0 0 1 0 8k (8192) cycles 64ms 0 0 1 1 16k (16384) cycles 0.125s 0 1 0 0 32k (32768) cycles 0.25s 0 1 0 1 64k (65536) cycles 0.5s 0 1 1 0 128k (131072) cycles 1.0s 0 1 1 1 256k (262144) cycles 2.0s 1 0 0 0 512k (524288) cycles 4.0s 1 0 0 1 1024k (1048576) cycles 8.0s 1010 reserved 1011 1100 1101 1110 1111
70 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13. i/o-ports 13.1 introduction all avr ports have true read-modify- w rite functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when chang- ing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin driver is stro ng enough to drive led displays directly. all port pins have indi- vidually selectable pull-up resistors with a suppl y-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 13-1 . refer to ?electrical char- acteristics? on page 367 for a complete list of parameters. figure 13-1. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? repre- sents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a progr am, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o regis- ters and bit locations are listed in ?table 13-34 and table 13-35 relates the alternate functions of port l to the overriding signals shown in figure 13-5 on page 76.? on page 99 . three i/o memory address locations are allocated for each port, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pi n x. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bit in the pi n x register, will result in a toggle in th e correspond- ing bit in the data register. in addition, the pu ll-up disable ? pud bit in mcucr disables the pull-up function for all pins in all ports when set. using the i/o port as general digital i/o is described in ?ports as general digital i/o? on page 71 . most port pins are multiplexed with alternate functions for the peripheral features on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 75 . refer to the individual module sectio ns for a full description of the alter- nate functions. c pin logic r pu s ee figure "general digital i/o" for details pxn
71 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. 13.2 ports as gener al digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 13-2 shows a func- tional description of one i/o-port pin, here generically called pxn. figure 13-2. general digital i/o (1) n ote: 1. w rx, w px, w dx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 13.2.1 configuring the pin each port pin consists of three register bits: ddxn, portxn, and pi n xn. as shown in ?table 13- 34 and table 13-35 relates the alternate function s of port l to the ov erriding signals shown in figure 13-5 on page 76.? on page 99 , the ddxn bits are accessed at the ddrx i/o address, the portxn bits at the portx i/o address, and the pi n xn bits at the pi n x i/o address. the ddxn bit in the ddrx register selects the direct ion of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is configured as an input pin. if portxn is written logic one when the pin is c onfigured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data bus sleep sleep: sleep control pxn i/o wpx 0 1 wrx wpx: write pinx register
72 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 if portxn is written logic one when the pin is conf igured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). 13.2.2 toggling the pin w riting a logic one to pi n xn toggles the value of portxn, independent on the value of ddrxn. n ote that the sbi instruction can be used to toggle one single bit in a port. 13.2.3 switching between input and output w hen switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled {ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) must occur. n ormally, the pull-up enabled state is fully accept- able, as a high-impedant enviro nment will not notice the differenc e between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register can be set to disable all pull-ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 13-1 summarizes the control signals for the pin value. 13.2.4 reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pi n xn register bit. as shown in figure 13-2 on page 71 , the pi n xn register bit and the preced- ing latch constitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 13-3 on page 73 shows a timing diagram of the synchroni zation when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. table 13-1. port pin configurations ddxn portxn pud (in mcucr) i/o pull-up comment 0 0 x input n o tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low 0 1 1 input n o tri-state (hi-z) 1 0 x output n o output low (sink) 1 1 x output n o output high (source)
73 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 13-3. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system cl ock. the latch is closed when the clock is low, and goes transpa rent when the clock is high, as indicated by the shaded region of the ?sy n c latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pi n xn register at the succeeding positive clock edge. as indi- cated by the two arrows tpd,max and tpd,min, a single signal tr ansition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. w hen reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 13-4 . the out instruction sets the ?sy n c latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is one system clock period. figure 13-4. synchronization when reading a software assigned pin value xxx in r17, pinx 0x00 0xff in s truction s s ync latch pinxn r17 xxx s y s tem clk t pd, max t pd, min out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
74 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the following code example shows how to set por t b pins 0 and 1 high, pins 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. n ote: 1. for the assembly program, two temporary re gisters are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the di rection bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 13.2.5 digital input enable and sleep modes as shown in figure 13-2 on page 71 , the digital input signal can be clamped to ground at the input of the schmitt-trigger. th e signal denoted sleep in the fi gure, is set by the mcu sleep controller in power-down mode, power-save mode, and standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as ex ternal interrupt pins. if the external interrupt request is not e nabled, sleep is active also for these pins. sl eep is also overri dden by various other alternate functions as described in ?alternate port functions? on page 75 . if a logic high level (?one?) is present on an asynchronous external interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 75 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 above mentioned sleep mode, as the clamping in these sleep mode produces the requested logic change. 13.2.6 unconnected pins if some pins are unused, it is recommended to ens ure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull-up will be disabled during reset. if low po wer consumption during reset is important, it is recommended to use an external pull-up or pull-down. connecting unused pins directly to v cc or g n d is not recommended, since this may ca use excessive currents if the pin is accidentally configured as an output. 13.3 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 13-5 on page 76 shows how the port pin control signals from the simplified figure 13-2 on page 71 can be overridden by alternate functions . the overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr microcon- troller family.
76 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 13-5. alternate port functions (1) n ote: 1. w rx, w px, w dx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data b u s 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn ptoexn: pxn, port toggle override enable wpx: write pinx wpx
77 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 13-2 summarizes the function of the overriding signals. the pin and port indexes from fig- ure 13-5 on page 76 are not shown in the succeeding tables. the overriding signals are generated internally in the modules having the alternate function. the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. refer to the alternate function description for further details. table 13-2. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardle ss of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov si gnal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state ( n ormal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regar dless of the mcu state ( n ormal mode, sleep mode). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog i nput/output to/from alte rnate functions. the signal is connected directly to the pad, and can be used bi- directionally.
78 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.1 alternate functions of port a the port a has an alternate function as the address low byte and data lines for the external memory interface. table 13-4 and table 13-5 on page 79 relates the alternate functions of port a to the overriding signals shown in figure 13-5 on page 76 . n ote: 1. ada is short for address active and repr esents the time when ad dress is output. see ?exter- nal memory interface? on page 28 for details. table 13-3. port a pins alternate functions port pin alternate function pa7 ad7 (external memory interface address and data bit 7) pa6 ad6 (external memory interface address and data bit 6) pa5 ad5 (external memory interface address and data bit 5) pa4 ad4 (external memory interface address and data bit 4) pa3 ad3 (external memory interface address and data bit 3) pa2 ad2 (external memory interface address and data bit 2) pa1 ad1 (external memory interface address and data bit 1) pa0 ad0 (external memory interface address and data bit 0) table 13-4. overriding signals for alternate functions in pa7:pa4 signal name pa7/ad7 pa6/ad6 pa5/ad5 pa4/ad4 puoe sre sre sre sre puov ~( w r | ada (1) ) ? porta7 ? pud ~( w r | ada) ? porta6 ? pud ~( w r | ada) ? porta5 ? pud ~( w r | ada) ? porta4 ? pud ddoe sre sre sre sre ddov w r | ada w r | ada w r | ada w r | ada pvoe sre sre sre sre pvov a7 ? ada | d7 output ? w r a6 ? ada | d6 output ? w r a5 ? ada | d5 output ? w r a4 ? ada | d4 output ? w r dieoe0000 dieov0000 di d7 i n put d6 i n put d5 i n put d4 i n put aio????
79 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.2 alternate functions of port b the port b pins with alternate functions are shown in table 13-6 . the alternate pin configuration is as follows: ? oc0a/oc1c/pcint7, bit 7 oc0a, output compare match a output: the pb7 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb7 set ?one?) to serve this function. the oc0a pin is also the output pin for the p w m mode timer function. oc1c, output compare match c output: the pb7 pi n can serve as an external output for the timer/counter1 output compare c. the pin has to be configured as an output (ddb7 set (one)) to serve this function. the oc1c pin is also the output pin for the p w m mode timer function. table 13-5. overriding signals for alternate functions in pa3:pa0 signal name pa3/ad3 pa2/ad2 pa1/ad1 pa0/ad0 puoe sre sre sre sre puov ~( w r | ada) ? porta3 ? pud ~( w r | ada) ? porta2 ? pud ~( w r | ada) ? porta1 ? pud ~( w r | ada) ? porta0 ? pud ddoe sre sre sre sre ddov w r | ada w r | ada w r | ada w r | ada pvoe sre sre sre sre pvov a3 ? ada | d3 output ? w r a2? ada | d2 output ? w r a1 ? ada | d1 output ? w r a0 ? ada | d0 output ? w r dieoe0000 dieov0000 di d3 i n put d2 i n put d1 i n put d0 i n put aio???? table 13-6. port b pins alternate functions port pin alternate functions pb7 oc0a/oc1c/pci n t7 (output compare and p w m output a for timer/counter0, output compare and p w m output c for timer/counter1 or pin change interrupt 7) pb6 oc1b/pci n t6 (output compare and p w m output b for timer/counter1 or pin change interrupt 6) pb5 oc1a/pci n t5 (output compare and p w m output a for timer/counter1 or pin change interrupt 5) pb4 oc2a/pci n t4 (output compare and p w m output a for timer/counter2 or pin change interrupt 4) pb3 miso/pci n t3 (spi bus master input/slave output or pin change interrupt 3) pb2 mosi/pci n t2 (spi bus master output/slave input or pin change interrupt 2) pb1 sck/pci n t1 (spi bus serial clock or pin change interrupt 1) pb0 ss /pci n t0 (spi slave select input or pin change interrupt 0)
80 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 pci n t7, pin change interrupt source 7: the pb7 pi n can serve as an external interrupt source. ? oc1b/pcint6, bit 6 oc1b, output compare match b output: the pb6 pin can serve as an external output for the timer/counter1 output compare b. the pin has to be configured as an output (ddb6 set (one)) to serve this function. the oc1b pin is also the output pin for the p w m mode timer function. pci n t6, pin change interrupt source 6: the pb6 pi n can serve as an external interrupt source. ? oc1a/pcint5, bit 5 oc1a, output compare match a output: the pb5 pin can serve as an external output for the timer/counter1 output compare a. the pin has to be configured as an output (ddb5 set (one)) to serve this function. the oc1a pin is also the output pin for the p w m mode timer function. pci n t5, pin change interrupt source 5: the pb5 pi n can serve as an external interrupt source. ? oc2a/pcint4, bit 4 oc2a, output compare match output: the pb4 pin can serve as an external output for the timer/counter2 output compare. the pin has to be configured as an output (ddb4 set (one)) to serve this function. the oc2a pin is also the output pin for the p w m mode timer function. pci n t4, pin change interrupt source 4: the pb4 pi n can serve as an external interrupt source. ? miso/pcint3 ? port b, bit 3 miso: master data input, slave data output pin for spi channel. w hen the spi is enabled as a master, this pin is configured as an in put regardless of the setting of ddb3. w hen the spi is enabled as a slave, the data direction of this pin is controlled by ddb3. w hen the pin is forced to be an input, the pull- up can still be controlled by the portb3 bit. pci n t3, pin change interrupt source 3: the pb3 pi n can serve as an external interrupt source. ? mosi/pcint2 ? port b, bit 2 mosi: spi master data output, slave data input for spi channel. w hen the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb2. w hen the spi is enabled as a master, the data direction of this pin is controlled by ddb2. w hen the pin is forced to be an input, the pull-up can st ill be controlled by the portb2 bit. pci n t2, pin change interrupt source 2: the pb2 pi n can serve as an external interrupt source. ? sck/pcint1 ? port b, bit 1 sck: master clock output, slave clock input pin for spi channel. w hen the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb1. w hen the spi0 is enabled as a master, the data direction of this pin is controlled by ddb1. w hen the pin is forced to be an input, the pull-up can st ill be controlled by the portb1 bit. pci n t1, pin change interrupt source 1: the pb1 pi n can serve as an external interrupt source. ?ss /pcint0 ? port b, bit 0 ss : slave port select input. w hen the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb0. as a slav e, the spi is activated when this pin is driven low. w hen the spi is enabled as a master, the data direct ion of this pin is controlled by ddb0. w hen the pin is forced to be an input, the pu ll-up can still be controlled by the portb0 bit.
81 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 13-7 and table 13-8 relate the alternate functions of port b to the overriding signals shown in figure 13-5 on page 76 . spi mstr i n put and spi slave output constitute the miso signal, while mosi is divided into spi mstr output and spi slave i n put. pci n t0, pin change interrupt source 0: the pb0 pi n can serve as an external interrupt source. table 13-7. overriding signals for alternate functions in pb7:pb4 signal name pb7/oc0a/oc1c pb6/oc1b pb5/oc1a pb4/oc2a puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc0/oc1c e n able oc1b e n able oc1a e n able oc2a e n able pvov oc0/oc1c oc1b oc1a oc2a dieoe pci n t7 ? pcie0 pci n t6 ? pcie0 pci n t5 ? pcie0 pci n t4 ? pcie0 dieov 1 1 1 1 di pci n t7 i n put pci n t6 i n put pci n t5 i n put pci n t4 i n put aio ? ? ? ? table 13-8. overriding signals for alternate functions in pb3:pb0 signal name pb3/miso pb2/mo si pb1/sck pb0/ss puoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr puov portb3 ? pud portb2 ? pud portb1 ? pud portb0 ? pud ddoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr ddov 0 0 0 0 pvoe spe ? mstr spe ? mstr spe ? mstr 0 pvov spi slave output spi mstr output sck output 0 dieoe pci n t3 ? pcie0 pci n t2 ? pcie0 pci n t1 ? pcie0 pci n t0 ? pcie0 dieov 1 1 1 1 di spi mstr i n put pci n t3 i n put spi slave i n put pci n t2 i n put sck i n put pci n t1 i n put spi ss pci n t0 i n put aio ? ? ? ?
82 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.3 alternate functions of port c the port c alternate function is as follows: table 13-10 and table 13-11 on page 83 relate the alternate functions of port c to the overriding signals shown in figure 13-5 on page 76 . table 13-9. port c pins alternate functions port pin alternate function pc7 a15 (external memory interface address bit 15) pc6 a14 (external memory interface address bit 14) pc5 a13 (external memory interface address bit 13) pc4 a12 (external memory interface address bit 12) pc3 a11 (external memory interface address bit 11) pc2 a10 (external memory interface address bit 10) pc1 a9 (external memory interface address bit 9) pc0 a8 (external memory interface address bit 8) table 13-10. overriding signals for alte rnate functions in pc7:pc4 signal name pc7/a15 pc6/a14 pc5/a13 pc4/a12 puoe sre ? (xmm<1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) puov 0 0 0 0 ddoe sre ? (xmm<1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) ddov 1 1 1 1 pvoe sre ? (xmm<1) sre ? (xmm<2) sre ? (xmm<3) sre ? (xmm<4) pvov a15 a14 a13 a12 dieoe 0 0 0 0 dieov 0 0 0 0 di ? ? ? ? aio ? ? ? ?
83 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.4 alternate functions of port d the port d pins with alternate functions are shown in table 13-12 . the alternate pin configuration is as follows: ? t0 ? port d, bit 7 t0, timer/counter0 counter source. ? t1 ? port d, bit 6 t1, timer/counter1 counter source. ? xck1 ? port d, bit 5 xck1, usart1 external clock. th e data direction register (ddd5) controls whether the clock is output (ddd5 set) or input (ddd5 cleared). the xck1 pin is active only when the usart1 operates in synchronous mode. ? icp1 ? port d, bit 4 icp1 ? input capture pin 1: the pd4 pin can ac t as an input capture pin for timer/counter1. table 13-11. overriding signals for alte rnate functions in pc3:pc0 signal name pc3/a11 pc2/a10 pc1/a9 pc0/a8 puoe sre ? (xmm<5) sre ? (xmm< 6) sre ? (xmm<7) sre ? (xmm<7) puov0000 ddoe sre ? (xmm<5) sre ? (xmm<6) sre ? (xmm<7) sre ? (xmm<7) ddov 1 1 1 1 pvoe sre ? (xmm<5) sre ? (xmm< 6) sre ? (xmm<7) sre ? (xmm<7) pvov a11 a10 a9 a8 dieoe0000 dieov0000 di???? aio???? table 13-12. port d pins alternate functions port pin alternate function pd7 t0 (timer/counter0 clock input) pd6 t1 (timer/counter1 clock input) pd5 xck1 (usart1 external clock input/output) pd4 icp1 (timer/counter1 input capture trigger) pd3 i n t3/txd1 (external interrupt3 input or usart1 transmit pin) pd2 i n t2/rxd1 (external interrupt2 input or usart1 receive pin) pd1 i n t1/sda (external interrupt1 input or t w i serial data) pd0 i n t0/scl (external interrupt0 input or t w i serial clock)
84 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? int3/txd1 ? port d, bit 3 i n t3, external interrupt source 3: the pd3 pin c an serve as an external interrupt source to the mcu. txd1, transmit data (data output pin for the usart1). w hen the usart1 transmitter is enabled, this pin is configured as an output regardless of the value of ddd3. ? int2/rxd1 ? port d, bit 2 i n t2, external interrupt source 2. the pd2 pin can serve as an external interrupt source to the mcu. rxd1, receive data (data input pin for the usart1). w hen the usart1 receiver is enabled this pin is configured as an input regardless of the value of ddd2. w hen the usart forces this pin to be an input, the pull-up can still be controlled by the portd2 bit. ? int1/sda ? port d, bit 1 i n t1, external interrupt source 1. the pd1 pin c an serve as an external interrupt source to the mcu. sda, 2-wire serial interface data: w hen the t w e n bit in t w cr is set (one) to enable the 2-wire serial interface, pin pd1 is disconnected from t he port and becomes the serial data i/o pin for the 2-wire serial interface. in this mode, ther e is a spike filter on the pin to suppress spikes shorter than 50ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. ?int0/scl ? port d, bit 0 i n t0, external interrupt source 0. the pd0 pin c an serve as an external interrupt source to the mcu. scl, 2-wire serial interface clock: w hen the t w e n bit in t w cr is set (one) to enable the 2- wire serial interface, pin pd0 is disconnect ed from the port and becomes the serial clock i/o pin for the 2-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorter than 50ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. table 13-13 on page 85 and table 13-14 on page 85 relates the alternate functions of port d to the overriding signals shown in figure 13-5 on page 76 .
85 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. w hen enabled, the 2-wire serial interface enable s slew-rate controls on the output pins pd0 and pd1. this is not shown in this table. in addition, spike filters are connected between the aio outputs shown in the port figure and the digital logic of the t w i module. table 13-13. overriding signals for alternate functions pd7:pd4 signal name pd7/t0 pd 6/t1 pd5/xck1 pd4/icp1 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 xck1 output e n able 0 ddov 0 0 1 0 pvoe 0 0 xck1 output e n able 0 pvov 0 0 xck1 output 0 dieoe 0 0 0 0 dieov 0 0 0 0 di t0 i n put t1 i n put xck1 i n put icp1 i n put aio ? ? ? ? table 13-14. overriding signals for alte rnate functions in pd3:pd0 (1) signal name pd3/int3/t xd1 pd2/int2/rxd1 pd1/int1/sda pd0/int0/scl puoe txe n 1rxe n 1t w e n t w e n puov 0 portd2 ? pud portd1 ? pud portd0 ? pud ddoe txe n 1rxe n 1t w e n t w e n ddov 1 0 sda_out scl_out pvoe txe n 10t w e n t w e n pvov txd1 0 0 0 dieoe i n t3 e n able i n t2 e n able i n t1 e n able i n t0 e n able dieov 1 1 1 1 di i n t3 i n put i n t2 i n put/rxd1 i n t1 i n put i n t0 i n put aio ? ? sda i n put scl i n put
86 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.5 alternate functions of port e the port e pins with alternate functions are shown in table 13-15 . n ote: 1. only for atmega1281/2561. for atmega640/ 1280/2560 these functions are placed on miso/mosi pins. ? int7/icp3/clko ? port e, bit 7 i n t7, external interrupt source 7: the pe7 pin can serve as an external interrupt source. icp3, input capture pin 3: the pe7 pin can act as an input capture pin for timer/counter3. clko - divided system clock: the divided system clock can be output on the pe7 pin. the divided system clock will be output if the ck out fuse is programmed, regardless of the porte7 and dde7 settings. it will also be output during reset. ? int6/t3 ? port e, bit 6 i n t6, external interrupt source 6: the pe6 pin can serve as an external interrupt source. t3, timer/counter3 counter source. ? int5/oc3c ? port e, bit 5 i n t5, external interrupt source 5: the pe5 pin can serve as an external interrupt source. oc3c, output compare match c output: the pe5 pin can serve as an external output for the timer/counter3 output compare c. the pin has to be configured as an output (dde5 set ?one?) to serve this function. the oc3c pin is also the output pin for the p w m mode timer function. table 13-15. port e pins alternate functions port pin alternate function pe7 i n t7/icp3/clk0 (external interrupt 7 input, timer/counter3 inpu t capture trigger or divided system clock) pe6 i n t6/ t3 (external interrupt 6 input or timer/counter3 clock input) pe5 i n t5/oc3c (external interrupt 5 input or output compare and p w m output c for timer/counter3) pe4 i n t4/oc3b (external interrupt4 input or output compare and p w m output b for timer/counter3) pe3 ai n 1/oc3a (analog comparator n egative input or output compare and p w m output a for timer/counter3) pe2 ai n 0/xck0 (analog comparator positive input or usart0 external clock input/output) pe1 pdo (1) /txd0 (programming data output or usart0 transmit pin) pe0 pdi (1) /rxd0/pci n t8 (programming data input, usart0 receive pin or pin change interrupt 8)
87 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? int4/oc3b ? port e, bit 4 i n t4, external interrupt source 4: the pe4 pin can serve as an external interrupt source. oc3b, output compare match b output: the pe4 pin can serve as an external output for the timer/counter3 output compare b. the pin has to be configured as an output (dde4 set (one)) to serve this function. the oc3b pin is also the output pin for the p w m mode timer function. ? ain1/oc3a ? port e, bit 3 ai n 1 ? analog comparator n egative input. this pin is directly connected to the negative input of the analog comparator. oc3a, output compare match a output: the pe3 pin can serve as an external output for the timer/counter3 output compare a. the pin has to be configured as an output (dde3 set ?one?) to serve this function. the oc3a pin is also the output pin for the p w m mode timer function. ? ain0/xck0 ? port e, bit 2 ai n 0 ? analog comparator positive input. this pi n is directly connected to the positive input of the analog comparator. xck0, usart0 external clock. th e data direction register (dde2) controls whether the clock is output (dde2 set) or input (dde2 cleared) . the xck0 pin is active only when the usart0 operates in synchronous mode. ? pdo/txd0 ? port e, bit 1 pdo, spi serial programming data output. duri ng serial program downloading, this pin is used as data output line for the atmega1281/2561. for atmega640/1280/2560 this function is placed on miso. txd0, usart0 transmit pin. ? pdi/rxd0/pcint8 ? port e, bit 0 pdi, spi serial programming data input. during serial program downloading, this pin is used as data input line for the atmega1281/2561. fo r atmega640/1280/2560 this function is placed on mosi. rxd0, usart0 receive pin. receive da ta (data input pin for the usart0). w hen the usart0 receiver is enabled this pin is configur ed as an input regardless of the value of ddre0. w hen the usart0 forces this pin to be an input, a logical one in porte0 will turn on the inter- nal pull-up. pci n t8, pin change interrupt source 8: the pe0 pi n can serve as an external interrupt source. table 13-16 on page 88 and table 13-17 on page 88 relates the alternate functions of port e to the overriding signals shown in figure 13-5 on page 76 .
88 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. pdo/pdi only available at pe1/pe0 for atmega1281/2561. table 13-16. overriding signals for alternate functions pe7:pe4 signal name pe7/int7/icp3 pe6/int6/t3 pe5/int5/oc3c pe4/int4/oc3b puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 oc3c e n able oc3b e n able pvov 0 0 oc3c oc3b dieoe i n t7 e n able i n t6 e n able i n t5 e n able i n t4 e n able dieov 1 1 1 1 di i n t7 i n put/icp3 i n put i n t7 i n put/t3 i n put i n t5 i n put i n t4 i n put aio ? ? ? ? table 13-17. overriding signals for alternate functions in pe3:pe0 signal name pe3/ain1/oc3a pe2/ain0/xck0 pe1/pdo (1) / txd0 pe0/pdi (1) / rxd0/pcint8 puoe 0 0 txe n 0rxe n 0 puov 0 0 0 porte0 ? pud ddoe 0 xck0 output e n able txe n 0rxe n 0 ddov 0 1 1 0 pvoe oc3b e n able xck0 output e n able txe n 00 pvov oc3b xck0 output txd0 0 dieoe 0 0 0 pci n t8 ? pcie1 dieov 0 0 0 1 di 0 xck0 i n put ? rxd0 pe0 0 0 0 pci n t8 i n put aio ai n 1 i n put ai n 0 i n put ? ?
89 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.6 alternate functions of port f the port f has an alternate function as analog input for the adc as shown in table 13-18 . if some port f pins are configured as outputs, it is essential that these do not switch when a con- version is in progress. this might corrupt the re sult of the conversion. if the jtag interface is enabled, the pull-up resistors on pins pf7(tdi), pf5(tms), an d pf4(tck) will be activated even if a reset occurs. ? tdi, adc7 ? port f, bit 7 adc7, analog to digital converter, channel 7. tdi, jtag test data in: serial input data to be shifted in to the instruction register or data reg- ister (scan chains). w hen the jtag interface is enabled, th is pin can not be used as an i/o pin. ? tdo, adc6 ? port f, bit 6 adc6, analog to digital converter, channel 6. tdo, jtag test data out: serial output data from instruction register or data register. w hen the jtag interface is enabled, this pin can not be used as an i/o pin. the tdo pin is tri-stated unless tap states that shift out data are entered. ? tms, adc5 ? port f, bit 5 adc5, analog to digital converter, channel 5. tms, jtag test mode select: this pin is used fo r navigating through the tap-controller state machine. w hen the jtag interface is enabled, this pin can not be used as an i/o pin. ? tck, adc4 ? port f, bit 4 adc4, analog to digital converter, channel 4. tck, jtag test clock: jtag oper ation is synchronous to tck. w hen the jtag interface is enabled, this pin can not be used as an i/o pin. ? adc3 ? adc0 ? port f, bit 3:0 analog to digital converter, channel 3:0. table 13-18. port f pins alternate functions port pin alternate function pf7 adc7/tdi (adc input channel 7 or jtag test data input) pf6 adc6/tdo (adc input channel 6 or jtag test data output) pf5 adc5/tms (adc input channel 5 or jtag test mode select) pf4 adc4/tck (adc input channel 4 or jtag test clock) pf3 adc3 (adc input channel 3) pf2 adc2 (adc input channel 2) pf1 adc1 (adc input channel 1) pf0 adc0 (adc input channel 0)
90 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.7 alternate functions of port g the port g alternate pin configuration is as follows: table 13-19. overriding signals for alternate functions in pf7:pf4 signal name pf7/adc7/tdi pf6/adc6/tdo pf5/adc5/tms pf4/adc4/tck puoe jtage n jtage n jtage n jtage n puov 1 0 1 1 ddoe jtage n jtage n jtage n jtage n ddov 0 shift_ir + shift_dr 00 pvoe 0 jtage n 00 pvov 0 tdo 0 0 dieoe jtage n jtage n jtage n jtage n dieov 0 0 0 0 di ? ? ? ? aio tdi/adc7 i n put adc6 i n put tms/adc5 i n put tck/adc4 i n put table 13-20. overriding signals for alternate functions in pf3:pf0 signal name pf3/adc3 pf2/adc2 pf1/ adc1 pf0/adc0 puoe0000 puov0000 ddoe0000 ddov0000 pvoe0000 pvov0000 dieoe0000 dieov0000 di???? aio adc3 i n put adc2 i n put adc1 i n put adc0 i n put table 13-21. port g pins alternate functions port pin alternate function pg5 oc0b (output compare and p w m output b for timer/counter0) pg4 tosc1 (rtc oscillator timer/counter2) pg3 tosc2 (rtc oscillator timer/counter2) pg2 ale (address latch enable to external memory) pg1 rd (read strobe to external memory) pg0 w r ( w rite strobe to external memory)
91 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? oc0b ? port g, bit 5 oc0b, output compare match b output: the pg5 pin can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddg5 set) to serve this function. the oc0b pin is also the output pin for the p w m mode timer function. ? tosc1 ? port g, bit 4 tosc2, timer oscillator pin 1: w hen the as2 bit in assr is se t (one) to enabl e asynchronous clocking of timer/counter2, pin pg4 is disconnected from the port, and becomes the input of the inverting oscillator amplifier. in this mode, a cr ystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? tosc2 ? port g, bit 3 tosc2, timer oscillator pin 2: w hen the as2 bit in assr is se t (one) to enabl e asynchronous clocking of timer/counter2, pin pg3 is disconnected from the port, and becomes the inverting output of the oscillator amplifier. in this mode , a crystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? ale ? port g, bit 2 ale is the external data memory address latch enable signal. ?rd ? port g, bit 1 rd is the external data memory read control strobe. ?wr ? port g, bit 0 w r is the external data memory write control strobe. table 13-22 on page 91 and table 13-23 on page 92 relates the alternate functions of port g to the overriding signals shown in figure 13-5 on page 76 . table 13-22. overriding signals for alternate functions in pg5:pg4 signal name ? ? pg5/ oc0b pg4/tosc1 puoe ? ? ? as2 puov??? 0 ddoe ? ? ? as2 ddov ? ? ? 0 pvoe ? ? oc0b enable 0 pvov ? ? oc0b 0 ptoe??? ? dieoe ? ? ? as2 dieov ? ? ? exclk di??? ? aio ? ? ? t/c2 osc i n put
92 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.8 alternate functions of port h the port h alternate pin configuration is as follows: ? t4 ? port h, bit 7 t4, timer/counter4 counter source. ? oc2b ? port h, bit 6 oc2b, output compare match b output: the ph6 pin can serve as an external output for the timer/counter2 output compare b. the pin has to be configured as an output (ddh6 set) to serve this function. the oc2b pin is also the output pin for the p w m mode timer function. ? oc4c ? port h, bit 5 oc4c, output compare match c output: the ph5 pin can serve as an external output for the timer/counter4 output compare c. the pin has to be configured as an output (ddh5 set) to serve this function. the oc4c pin is also the output pin for the p w m mode timer function. table 13-23. overriding signals for alternate functions in pg3:pg0 signal name pg3/tosc2 pg2/ale/a7 pg1/rd pg0/wr puoe as2 ? exclk sre sre sre puov0 000 ddoe as2 ? exclk sre sre sre ddov 0 1 1 1 pvoe 0 sre sre sre pvov 0 ale rd w r ptoe? ??? dieoe as2 ? exclk 000 dieov0 000 di ? ??? aio t/c2 osc output ? ? ? table 13-24. port h pins alternate functions port pin alternate function ph7 t4 (timer/counter4 clock input) ph6 oc2b (output compare and p w m output b for timer/counter2) ph5 oc4c (output compare and p w m output c for timer/counter4) ph4 oc4b (output compare and p w m output b for timer/counter4) ph3 oc4a (output compare and p w m output a for timer/counter4) ph2 xck2 (usart2 external clock) ph1 txd2 (usart2 transmit pin) ph0 rxd2 (usart2 receive pin)
93 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? oc4b ? port h, bit 4 oc4b, output compare match b output: the ph4 pin can serve as an external output for the timer/counter2 output compare b. the pin has to be configured as an output (ddh4 set) to serve this function. the oc4b pin is also the output pin for the p w m mode timer function. ? oc4a ? port h, bit 3 oc4c, output compare match a output: the ph3 pi n can serve as an external output for the timer/counter4 output compare a. the pin has to be configured as an output (ddh3 set) to serve this function. the oc4a pin is also the output pin for the p w m mode timer function. ? xck2 ? port h, bit 2 xck2, usart2 external clock: the data direction register (ddh2) controls whether the clock is output (ddh2 set) or input (ddh2 cleared). the xc2k pin is active only when the usart2 operates in synchronous mode. ? txd2 ? port h, bit 1 txd2, usart2 transmit pin. ? rxd2 ? port h, bit 0 rxd2, usart2 receive pin: receive da ta (data input pin for the usart2). w hen the usart2 receiver is enabled, this pin is configured as an inpu t regardless of the value of ddh0. w hen the usart2 forces this pin to be an input, a logical on in porth0 will turn on the internal pull-up. table 13-25. overriding signals for alte rnate functions in ph7:ph4 signal name ph7/t4 ph6/oc2b ph5/oc4c ph4/oc4b puoe0 000 puov0 000 ddoe 0 0 0 0 ddov0 000 pvoe 0 oc2b e n able oc4c e n able oc4b e n able pvov 0 oc2b oc4c oc4b ptoe? ??? dieoe0 000 dieov0 000 di t4 i n put000 aio? ???
94 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.9 alternate functions of port j the port j alternate pin configuration is as follows: ? pcint15:12 - port j, bit 6:3 pci n t15:12, pin change interrupt source 15:12. the pj6:3 pins can serve as external interrupt sources. ? xck2/pcint11 - port j, bit 2 xck2, usart 2 external clock. the data directi on register (ddj2) controls whether the clock is output (ddj2 set) or input (ddj2 cleared). the xck2 pin is active only when the usart2 operates in synchronous mode. pci n t11, pin change interrupt source 11. the pj2 pin can serve as external interrupt sources. table 13-26. overriding signals for alte rnate functions in ph3:ph0 signal name ph3/oc4a ph 2/xck2 ph1/txd2 ph0/rxd2 puoe 0 0 txe n 2rxe n 2 puov 0 0 0 porth0 ? pud ddoe 0 xck2 output e n able txe n 2rxe n 2 ddov0 110 pvoe oc4a e n able xck2 output e n able txe n 20 pvov oc4a xck2 txd2 0 ptoe? ??? dieoe0 000 dieov0 000 di 0 xc2k i n put 0 rxd2 aio? ??? table 13-27. port j pins alternate functions port pin alternate function pj7 ? pj6 pci n t15 (pin change interrupt 15) pj5 pci n t14 (pin change interrupt 14) pj4 pci n t13 (pin change interrupt 13) pj3 pci n t12 (pin change interrupt 12) pj2 xck3/pci n t11 (usart3 external clock or pin change interrupt 11) pj1 txd3/pci n t10 (usart3 transmit pin or pin change interrupt 10) pj0 rxd3/pci n t9 (usart3 receive pin or pin change interrupt 9)
95 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? txd3/pcint10 - port j, bit 1 txd3, usart3 transmit pin. pci n t10, pin change interrupt source 10. the pj1 pin can serve as external interrupt sources. ? rxd3/pcint9 - port j, bit 0 rxd3, usart3 receive pin. receive da ta (data input pin for the usart3). w hen the usart3 receiver is enabled, this pin is config ured as an input regardless of the value of ddj0. w hen the usart3 forces th is pin to be an input, a logical on e in portj0 will tu rn on the inter- nal pull-up. pci n t9, pin change interrupt source 9. the pj0 pin can serve as external interrupt sources. table 13-28 on page 96 and table 13-29 on page 96 relates the alternate functions of port j to the overriding signals shown in figure 13-5 on page 76 .
96 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.10 alternate functions of port k the port k alternate pin configuration is as follows: table 13-28. overriding signals for alternate functions in pj7:pj4 signal name pj7 pj6/ pcint1 5 pj5/ pcint14 pj4/ pcint13 puoe0000 puov0000 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe0000 pvov0000 ptoe---- dieoe 0 pci n t15pcie1 pci n t14pcie1 pci n t13pcie1 dieov 0 1 1 1 di 0 pci n t15 i n put pci n t14 i n put pci n t13 i n put aio - - - - table 13-29. overriding signals for alternate functions in pj3:pj0 signal name pj3/pcint12 pj2/xck3/pcint 11 pj1/txd3/pcint 10 pj0/rxd3/pcint 9 puoe 0 0 txe n 3rxe n 3 puov000portj0pud ddoe 0 xck3 output e n able txe n 3rxe n 3 ddov0110 pvoe 0 xck3 output e n able txe n 30 pvov 0 xck3 txd3 0 ptoe---- dieoe pci n t12pcie1 pci n t11pcie1 pci n t10pcie1 pci n t9pcie1 dieov1111 di pci n t12 i n put pci n t11 i n put xck3 i n put pci n t10 i n put pci n t9 i n put rxd3 aio---- table 13-30. port k pins alternate functions port pin alternate function pk7 adc15/pci n t23 (adc input channel 15 or pin change interrupt 23) pk6 adc14/pci n t22 (adc input channel 14 or pin change interrupt 22) pk5 adc13/pci n t21 (adc input channel 13 or pin change interrupt 21)
97 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? adc15:8/pcint23:16 ? port k, bit 7:0 adc15:8, analog to digital converter, channel 15 - 8. pci n t23:16, pin change interrupt source 23:16. the pk7:0 pins can serve as external inter- rupt sources. pk4 adc12/pci n t20 (adc input channel 12 or pin change interrupt 20) pk3 adc11/pci n t19 (adc input channel 11 or pin change interrupt 19) pk2 adc10/pci n t18 (adc input channel 10 or pin change interrupt 18) pk1 adc9/pci n t17 (adc input channel 9 or pin change interrupt 17) pk0 adc8 /pci n t16 (adc input channel 8 or pin change interrupt 16) table 13-31. overriding signals for alternate functions in pk7:pk4 signal name pk7/adc15/ pcint23 pk6/adc14/ pcint22 pk5/adc13/ pcint21 pk4/adc12/ pcint20 puoe0000 puov0000 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe0000 pvov0000 ptoe???? dieoe pci n t23 ? pcie2 pci n t22 ? pcie2 pci n t21 ? pcie2 pci n t20 ? pcie2 dieov 1 1 1 1 di pci n t23 i n put pci n t22 i n put pci n t21 i n put pci n t20 i n put aio adc15 i n put adc14 i n put adc13 i n put adc12 i n put table 13-30. port k pins alternate functions (continued) port pin alternate function
98 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.3.11 alternate functions of port l the port l alternate pin configuration is as follows: ? oc5c ? port l, bit 5 oc5c, output compare match c output: the pl5 pin can serve as an external output for the timer/counter5 output compare c. the pin has to be configured as an output (ddl5 set) to serve this function. the oc5c pin is also the output pin for the p w m mode timer function. ? oc5b ? port l, bit 4 oc5b, output compare match b output: the pl4 pin can serve as an external output for the timer/counter 5 output compare b. the pin has to be configured as an output (ddl4 set) to serve this function. the oc5b pin is also the output pin for the p w m mode timer function. ? oc5a ? port l, bit 3 oc5a, output compare match a output: the pl3 pin can serve as an external output for the timer/counter 5 output compare a. the pin has to be configured as an output (ddl3 set) to serve this function. the oc5a pin is also the output pin for the p w m mode timer function. table 13-32. overriding signals for alternate functions in pk3:pk0 signal name pk3/adc11/ pcint19 pk2/adc10/ pcint18 pk1/adc9/ pcint17 pk0/adc8/ pcint16 puoe0000 puov0000 ddoe0000 ddov 0 0 0 0 pvoe0000 pvov0000 ptoe???? dieoe pci n t19 ? pcie2 pci n t18 ? pcie2 pci n t17 ? pcie2 pci n t16 ? pcie2 dieov 1 1 1 1 di pci n t19 i n put pci n t18 i n put pci n t17 i n put pci n t16 i n put aio adc11 i n put adc10i n put adc9 i n put adc8 i n put table 13-33. port l pins alternate functions port pin alternate function pl7 ? pl6 ? pl5 oc5c (output compare and p w m output c for timer/counter5) pl4 oc5b (output compare and p w m output b for timer/counter5) pl3 oc5a (output compare and p w m output a for timer/counter5) pl2 t5 (timer/counter5 clock input) pl1 icp5 (timer/counter5 input capture trigger) pl0 icp4 (timer/counter4 input capture trigger)
99 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? t5 ? port l, bit 2 t5, timer/counter5 counter source. ? icp5 ? port l, bit 1 icp5, input capture pin 5: the pl1 pin can serve as an input capture pin for timer/counter5. ? icp4 ? port l, bit 0 icp4, input capture pin 4: the pl0 pin can serve as an input capture pin for timer/counter4. table 13-34 and table 13-35 relates the alternate functions of port l to the overriding signals shown in figure 13-5 on page 76 . table 13-34. overriding signals for alternate functions in pl7:pl4 signal name pl7 pl6 pl5/oc5c pl4/oc5b puoe0000 puov0000 ddoe ? ? 0 0 ddov ? ? 0 0 pvoe ? ? oc5c enable oc5b enable pvov ? ? oc5c oc5b ptoe???? dieoe 0 0 0 0 dieov 0 0 0 0 di0000 aio ? ? ? ? table 13-35. overriding signals for alternate functions in pl3:pl0 signal name pl 3/oc5a pl2/t5 pl 1/icp5 pl0/icp4 puoe0000 puov0000 ddoe0000 ddov0000 pvoe oc5a e n able 0 0 0 pvovoc5a000 ptoe???? dieoe0000 dieov0000 di 0 t5 i n put icp5 i n put icp4 i n put aio????
100 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.4 register descrip tion for i/o-ports 13.4.1 mcucr ? mcu control register ? bit 4 ? pud: pull-up disable w hen this bit is written to one, the i/o ports pull-up resistors are disabled even if the ddxn and portxn registers are configured to enable the pull-up resistor ({ddxn, portxn} = 0b01). see ?configuring the pin? on page 71 for more details about this feature. 13.4.2 porta ? port a data register 13.4.3 ddra ? port a data direction register 13.4.4 pina ? port a input pins address 13.4.5 portb ? port b data register 13.4.6 ddrb ? port b data direction register 13.4.7 pinb ? port b input pins address bit 7 6 5 4 3 2 1 0 0x35 (0x55) jtd ? ?pud ? ? ivsel ivce mcucr read/ w rite r/ w rrr/ w rrr/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x02 (0x22) porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 porta read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x01 (0x21) dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 ddra read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x00 (0x20) pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 pina read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 0x05 (0x25) portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x04 (0x24) ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x03 (0x23) pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 pinb read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a
101 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.4.8 portc ? port c data register 13.4.9 ddrc ? port c data direction register 13.4.10 pinc? port c input pins address 13.4.11 portd ? port d data register 13.4.12 ddrd ? port d data direction register 13.4.13 pind ? port d input pins address 13.4.14 porte ? port e data register 13.4.15 ddre ? port e data direction register bit 76543210 0x08 (0x28) portc7 portc6 portc5 portc4 portc3 portc2 portc1 portc0 portc read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x07 (0x27) ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 ddrc read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x06 (0x26) pinc7 pinc6 pinc5 pinc4 pinc3 pinc2 pinc1 pinc0 pinc read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 0x0b (0x2b) portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 portd read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x0a (0x2a) ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x09 (0x29) pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 pind read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 0x0e (0x2e) porte7 porte6 porte5 porte4 porte3 porte2 porte1 porte0 porte read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x0d (0x2d) dde7 dde6 dde5 dde4 dde3 dde2 dde1 dde0 ddre read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
102 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.4.16 pine ? port e input pins address 13.4.17 portf ? port f data register 13.4.18 ddrf ? port f data direction register 13.4.19 pinf ? port f input pins address 13.4.20 portg ? port g data register 13.4.21 ddrg ? port g data direction register 13.4.22 ping ? port g input pins address 13.4.23 porth ? port h data register bit 76543210 0x0c (0x2c) pine7 pine6 pine5 pine4 pine3 pine2 pine1 pine0 pine read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 0x11 (0x31) portf7 portf6 portf5 portf4 portf3 portf2 portf1 portf0 portf read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x10 (0x30) ddf7 ddf6 ddf5 ddf4 ddf3 ddf2 ddf1 ddf0 ddrf read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x0f (0x2f) pinf7 pinf6 pinf5 pinf4 pinf3 pinf2 pinf1 pinf0 pinf read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 0x14 (0x34) ?? portg5 portg4 portg3 portg2 portg1 portg0 portg read/ w rite r r r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x13 (0x33) ? ? ddg5 ddg4 ddg3 ddg2 ddg1 ddg0 ddrg read/ w rite r r r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x12 (0x32) ? ? ping5 ping4 ping3 ping2 ping1 ping0 ping read/ w rite r r r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 n /a n /a n /a n /a n /a n /a bit 76543210 (0x102) porth7 porth6 porth5 porth4 porth3 porth2 porth1 porth0 porth read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
103 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.4.24 ddrh ? port h data direction register 13.4.25 pinh ? port h input pins address 13.4.26 portj ? port j data register 13.4.27 ddrj ? port j data direction register 13.4.28 pinj ? port j input pins address 13.4.29 portk ? port k data register 13.4.30 ddrk ? port k data direction register 13.4.31 pink ? port k input pins address bit 76543210 (0x101) ddh7 ddh6 ddh5 ddh4 ddh3 ddh2 ddh1 ddh0 ddrh read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x100) pinh5 pinh5 pinh5 pinh4 pi nh3 pingh pinh1 pinh0 pinh read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 (0x105) portj7 portj6 portj5 portj4 portj3 portj2 portj1 portj0 portj read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x104) ddj7 ddj6 ddj5 ddj4 ddj3 ddj2 ddj1 ddj0 ddrj read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x103) pinj5 pinj5 pinj5 pinj4 pinj3 pingj pinj1 pinj0 pinj read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a bit 76543210 (0x108) portk7 portk6 portk5 portk4 portk3 portk2 portk1 portk0 portk read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x107) ddk7 ddk6 ddk5 ddk4 ddk3 ddk2 ddk1 ddk0 ddrk read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x106) pink5 pink5 pink5 pink4 pi nk3 pingk pink1 pink0 pink read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a
104 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 13.4.32 portl ? port l data register 13.4.33 ddrl ? port l data direction register 13.4.34 pinl ? port l input pins address bit 76543210 (0x10b) portl7 portl6 portl5 portl4 portl3 portl2 portl1 portl0 portl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x10a) ddl7 ddl6 ddl5 ddl4 ddl3 ddl2 ddl1 ddl0 ddrl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x109) pinl5 pinl5 pinl5 pinl4 pinl3 pingl pinl1 pinl0 pinl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value n /a n /a n /a n /a n /a n /a n /a n /a
105 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 14. interrupts this section describes the specifics of the interrupt handling as performed in atmega640/1280/1281/2560/2561. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt handling? on page 18 . 14.1 interrupt vectors in atmega640/1280/ 1281/2560/2561 table 14-1. reset and interrupt vectors vector no. program address (2) source interrupt definition 1 $0000 (1) reset external pin, power-on reset, brown-out reset, w atchdog reset, and jtag avr reset 2 $0002 i n t0 external interrupt request 0 3 $0004 i n t1 external interrupt request 1 4 $0006 i n t2 external interrupt request 2 5 $0008 i n t3 external interrupt request 3 6 $000a i n t4 external interrupt request 4 7 $000c i n t5 external interrupt request 5 8 $000e i n t6 external interrupt request 6 9 $0010 i n t7 external interrupt request 7 10 $0012 pci n t0 pin change interrupt request 0 11 $0014 pci n t1 pin change interrupt request 1 12 $0016 (3) pci n t2 pin change interrupt request 2 13 $0018 w dt w atchdog time-out interrupt 14 $001a timer2 compa timer /counter2 compare match a 15 $001c timer2 compb timer /counter2 compare match b 16 $001e timer2 ovf timer/counter2 overflow 17 $0020 timer1 capt timer/counter1 capture event 18 $0022 timer1 compa timer /counter1 compare match a 19 $0024 timer1 compb timer /counter1 compare match b 20 $0026 timer1 compc timer/counter1 compare match c 21 $0028 timer1 ovf timer/counter1 overflow 22 $002a timer0 compa timer /counter0 compare match a 23 $002c timer0 compb timer /counter0 compare match b 24 $002e timer0 ovf timer/counter0 overflow 25 $0030 spi, stc spi serial transfer complete 26 $0032 usart0 rx usart0 rx complete 27 $0034 usart0 udre usart0 data register empty 28 $0036 usart0 tx usart0 tx complete 29 $0038 a n alog comp analog comparator
106 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. w hen the bootrst fuse is programmed, the device will jump to the boot loader address at reset, see ?memory programming? on page 335 . 2. w hen the ivsel bit in mcucr is set, interrupt ve ctors will be moved to the start of the boot flash section. the address of each interrupt vector will then be the address in this table added to the start address of the boot flash section. 3. only available in atmega640/1280/2560. 30 $003a adc adc conversion complete 31 $003c ee ready eeprom ready 32 $003e timer3 capt timer/counter3 capture event 33 $0040 timer3 compa timer/counter3 compare match a 34 $0042 timer3 compb timer/counter3 compare match b 35 $0044 timer3 compc timer/counter3 compare match c 36 $0046 timer3 ovf timer/counter3 overflow 37 $0048 usart1 rx usart1 rx complete 38 $004a usart1 udre usart1 data register empty 39 $004c usart1 tx usart1 tx complete 40 $004e t w i 2-wire serial interface 41 $0050 spm ready store program memory ready 42 $0052 (3) timer4 capt timer/counter4 capture event 43 $0054 timer4 compa timer/counter4 compare match a 44 $0056 timer4 compb timer/counter4 compare match b 45 $0058 timer4 compc timer/counter4 compare match c 46 $005a timer4 ovf timer/counter4 overflow 47 $005c (3) timer5 capt timer/counter5 capture event 48 $005e timer5 compa timer/counter5 compare match a 49 $0060 timer5 compb timer/counter5 compare match b 50 $0062 timer5 compc timer/counter5 compare match c 51 $0064 timer5 ovf timer/counter5 overflow 52 $0066 (3) usart2 rx usart2 rx complete 53 $0068 (3) usart2 udre usart2 data register empty 54 $006a (3) usart2 tx usart2 tx complete 55 $006c (3) usart3 rx usart3 rx complete 56 $006e (3) ) usart3 udre usart3 data register empty 57 $0070 (3) usart3 tx usart3 tx complete table 14-1. reset and interrupt vectors (continued) vector no. program address (2) source interrupt definition
107 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 14.2 reset and interr upt vector placement table 14-2 shows reset and interrupt vectors placement for the various combinations of bootrst and ivsel settings. if the program never enables an in terrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application section while the interrupt vectors are in the boot section or vice versa. n ote: 1. the boot reset address is shown in table 29-7 on page 328 through table 29-15 on page 332 . for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. the most typical and general program setup for the reset and interrupt vector addresses in atmega640/1280/1281/2560/2561 is: table 14-2. reset and interrupt vectors placement (1) bootrst ivsel reset address interrupt vectors start address 1 0 0x0000 0x0002 1 1 0x0000 boot reset address + 0x0002 0 0 boot reset address 0x0002 0 1 boot reset address boot reset address + 0x0002 address labels code comments 0x0000 jmp reset ; reset handler 0x0002 jmp int0 ; irq0 handler 0x0004 jmp int1 ; irq1 handler 0x0006 jmp int2 ; irq2 handler 0x0008 jmp int3 ; irq3 handler 0x000a jmp int4 ; irq4 handler 0x000c jmp int5 ; irq5 handler 0x000e jmp int6 ; irq6 handler 0x0010 jmp int7 ; irq7 handler 0x0012 jmp pcint0 ; pcint0 handler 0x0014 jmp pcint1 ; pcint1 handler 0x0016 jmp pcint2 ; pcint2 handler 0x0018 jmp wdt ; watchdog timeout handler 0x001a jmp tim2_compa ; timer2 comparea handler 0x001c jmp tim2_compb ; timer2 compareb handler 0x001e jmp tim2_ovf ; timer2 overflow handler 0x0020 jmp tim1_capt ; timer1 capture handler 0x0022 jmp tim1_compa ; timer1 comparea handler 0x0024 jmp tim1_compb ; timer1 compareb handler 0x0026 jmp tim1_compc ; timer1 comparec handler 0x0028 jmp tim1_ovf ; timer1 overflow handler 0x002a jmp tim0_compa ; timer0 comparea handler 0x002c jmp tim0_compb ; timer0 compareb handler 0x002e jmp tim0_ovf ; timer0 overflow handler 0x0030 jmp spi_stc ; spi transfer complete handler 0x0032 jmp usart0_rxc ; usart0 rx complete handler 0x0034 jmp usart0_udre ; usart0,udr empty handler 0x0036 jmp usart0_txc ; usart0 tx complete handler 0x0038 jmp ana_comp ; analog comparator handler 0x003a jmp adc ; adc conversion complete handler 0x003c jmp ee_rdy ; eeprom ready handler 0x003e jmp tim3_capt ; timer3 capture handler
108 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w hen the bootrst fuse is unprogrammed, the boot section size set to 8kbytes and the ivsel bit in the mcucr register is set before an y interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses is: address labels code comments 0x00000 reset: ldi r16,high(ramend); main program start 0x00001 out sph,r16 ; set stack pointer to top of ram 0x00002 ldi r16,low(ramend) 0x00003 out spl,r16 0x00004 sei ; enable interrupts 0x00005 xxx ; .org 0x1f002 0x1f002 jmp ext_int0 ; irq0 handler 0x1f004 jmp ext_int1 ; irq1 handler ... ... ... ; 0x1fo70 jmp usart3_txc ; usart3 tx complete handler 0x0040 jmp tim3_compa ; timer3 comparea handler 0x0042 jmp tim3_compb ; timer3 compareb handler 0x0044 jmp tim3_compc ; timer3 comparec handler 0x0046 jmp tim3_ovf ; timer3 overflow handler 0x0048 jmp usart1_rxc ; usart1 rx complete handler 0x004a jmp usart1_udre ; usart1,udr empty handler 0x004c jmp usart1_txc ; usart1 tx complete handler 0x004e jmp twi ; 2-wire serial handler 0x0050 jmp spm_rdy ; spm ready handler 0x0052 jmp tim4_capt ; timer4 capture handler 0x0054 jmp tim4_compa ; timer4 comparea handler 0x0056 jmp tim4_compb ; timer4 compareb handler 0x0058 jmp tim4_compc ; timer4 comparec handler 0x005a jmp tim4_ovf ; timer4 overflow handler 0x005c jmp tim5_capt ; timer5 capture handler 0x005e jmp tim5_compa ; timer5 comparea handler 0x0060 jmp tim5_compb ; timer5 compareb handler 0x0062 jmp tim5_compc ; timer5 comparec handler 0x0064 jmp tim5_ovf ; timer5 overflow handler 0x0066 jmp usart2_rxc ; usart2 rx complete handler 0x0068 jmp usart2_udre ; usart2,udr empty handler 0x006a jmp usart2_txc ; usart2 tx complete handler 0x006c jmp usart3_rxc ; usart3 rx complete handler 0x006e jmp usart3_udre ; usart3,udr empty handler 0x0070 jmp usart3_txc ; usart3 tx complete handler ; 0x0072 reset: ldi r16, high(ramend) ; main program start 0x0073 out sph,r16 ; set stack pointer to top of ram 0x0074 ldi r16, low(ramend) 0x0075 out spl,r16 0x0076 sei ; enable interrupts 0x0077 xxx ... ... ... ...
109 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w hen the bootrst fuse is programmed and the boot section size set to 8kbytes, the most typical and general program setup for the reset and interrupt vector addresses is: address labels code comments .org 0x0002 0x00002 jmp ext_int0 ; irq0 handler 0x00004 jmp ext_int1 ; irq1 handler ... ... ... ; 0x00070 jmp usart3_txc ; usart3 tx complete handler ; .org 0x1f000 0x1f000 reset: ldi r16,high(ramend); main program start 0x1f001 out sph,r16 ; set stack pointer to top of ram 0x1f002 ldi r16,low(ramend) 0x1f003 out spl,r16 0x1f004 sei ; enable interrupts 0x1f005 xxx w hen the bootrst fuse is programmed, the boot section size set to 8kbytes and the ivsel bit in the mcucr register is set before any interr upts are enabled, the mo st typical and general program setup for the reset and interrupt vector addresses is: address labels code comments ; .org 0x1f000 0x1f000 jmp reset ; reset handler 0x1f002 jmp ext_int0 ; irq0 handler 0x1f004 jmp ext_int1 ; irq1 handler ... ... ... ; 0x1f070 jmp usart3_txc ; usart3 tx complete handler ; 0x1f072 reset: ldi r16,high(ramend) ; main program start 0x1f073 out sph,r16 ; set stack pointer to top of ram 0x1f074 ldi r16,low(ramend) 0x1f075 out spl,r16 0x1f076 sei ; enable interrupts 0x1fo77 xxx 14.3 moving interrupts between a pplication and boot section the mcu control register controls the placement of the interrupt vector table, see code exam- ple below. for more details, see ?reset and interrupt handling? on page 18 .
110 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 14.4 register description 14.4.1 mcucr ? mcu control register ? bit 1 ? ivsel: interrupt vector select w hen the ivsel bit is clea red (zero), the interrupt vectors ar e placed at the st art of the flash memory. w hen this bit is set (one), the interrupt vectors are moved to the beginning of the boot loader section of the flash. the actual address of the start of the boot flash section is deter- mined by the bootsz fuses. refer to the section ?memory programming? on page 335 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit (see ?moving interrupts between application and boot sec- tion? on page 109 ): 1. w rite the interrupt vector change enable (ivce) bit to one. 2. w ithin four cycles, write the desired value to ivsel while writing a zero to ivce. assembly code example move_interrupts: ; get mcucr in r16, mcucr mov r17, r16 ; enable change of interrupt vectors ori r16, (1< 111 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 interrupts will automatically be di sabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabl ed until after the instru ction following the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. n ote: if interrupt vectors are placed in the boot loader section and boot lock bit blb02 is programmed, interrupts are disabled while executing from the a pplication section. if interrupt vectors are placed in the application section and boot lock bit blb 12 is programed, interrupts are disabled while executing from the boot loader section. refer to the section ?memory programmi ng? on page 335 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of the ivsel bit. ivce is cleared by hardware four cyc les after it is written or when ivsel is written. sett ing the ivce bit will disable interrupts, as explained in the ivsel description.
112 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 15. external interrupts the external interrupts are triggered by the i n t7:0 pin or any of the pci n t23:0 pins. observe that, if enabled, the interrupts will trigger even if the i n t7:0 or pci n t23:0 pins are configured as outputs. this feature provides a way of generating a software interrupt. the pin change interrupt pci2 wi ll trigger if any enabled pci n t23:16 pin toggles, pin change interrupt pci1 if any enabled pci n t15:8 toggles and pin change interrupts pci0 will trigger if any enabled pci n t7:0 pin toggles. pcmsk2, pcmsk1 and pcmsk0 registers control which pins contribute to the pin change interrupts. pin change interrupts on pci n t23 :0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the external interrupts can be triggered by a falli ng or rising edge or a low level. this is set up as indicated in the specification for the external interrupt control registers ? eicra (i n t3:0) and eicrb (i n t7:4). w hen the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. n ote that recognition of falling or rising edge interrupts on i n t7:4 requires the presence of an i/o clock, described in ?overview? on page 40 . low level interrupts and the edge interrupt on i n t3:0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. n ote that if a level triggered interrupt is used for wake-up from power-down, the required level must be held long enough for the mcu to complete the wake-up to trigger the level interrupt. if the level disappears before the end of the start-up ti me, the mcu will still wake up, but no inter- rupt will be generated. the start- up time is defined by the su t and cksel fuses as described in ?system clock and clock options? on page 40 . 15.1 pin change interrupt timing an example of timing of a pin change interrupt is shown in figure 15-1 on page 113 .
113 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 15-1. n ormal pin change interrupt. 15.2 register description 15.2.1 eicra ? external interrupt control register a the external interrupt control register a contains control bits for interrupt sense control. ? bits 7:0 ? isc31, isc30 ? isc00, isc00: external interrupt 3 - 0 sense control bits the external interrupts 3 - 0 are activated by the external pins i n t3:0 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 15-1 on page 114 . edges on i n t3:0 are registered asynchronously. pulses on i n t3:0 pins wider than the minimum pulse width given in table 15-2 on page 114 will generate an interrupt. shorter pulses are not guaranteed to generate an inter- rupt. if low level interrupt is se lected, the low level must be held until the completion of the currently executing instru ction to generate an interrupt. if e nabled, a level trig gered inte rrupt will generate an interrupt request as long as the pin is held low. w hen changing the iscn bit, an interrupt can occur. therefore, it is recommended to first disable i n tn by clearing its interrupt enable bit in the eimsk register. then, the iscn bit can be changed. finally, the i n tn interrupt flag should be cleared by writing a logical one to its interrupt flag bit (i n tfn) in the eifr regis- ter before the interrupt is re-enabled. clk pcint(n) pin_lat pin_sync pcint_in_(n) pcint_syn pcint_setflag pcif pcint(0) pin_sync pcint_syn pin_lat d q le pcint_setflag pcif clk clk pcint(0) in pcm s k(x) pcint_in_(0) 0 x bit 76543210 (0x69) isc31isc30isc21isc20isc11isc10isc01isc00 eicra read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
114 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. n = 3, 2, 1or 0. w hen changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. 15.2.2 eicrb ? external interrupt control register b ? bits 7:0 ? isc71, isc70 - isc41, isc40: external interrupt 7 - 4 sense control bits the external interrupts 7 - 4 are activated by the external pins i n t7:4 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 15-3 . the value on the i n t7:4 pins are sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an inter- rupt. observe that cpu clock frequency can be lower than the xtal frequency if the xtal divider is enabled. if low level interrupt is se lected, the low level must be held until the comple- tion of the currently executing instruction to generate an interrupt. if enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. n ote: 1. n = 7, 6, 5 or 4. w hen changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. table 15-1. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of i n tn generates an interrupt request 0 1 any edge of i n tn generates asynchronously an interrupt request 1 0 the falling edge of i n tn generates asynchronously an interrupt request 1 1 the rising edge of i n tn generates asynchronously an interrupt request table 15-2. asynchronous external interrupt characteristics symbol parameter condition min typ max units t i n t minimum pulse width for asynchronous external interrupt 50 ns bit 76543210 (0x6a) isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 eicrb read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 table 15-3. interrupt sense control (1) iscn1 iscn0 description 0 0 the low level of i n tn generates an interrupt request 0 1 any logical change on i n tn generates an interrupt request 1 0 the falling edge between two samples of i n tn generates an interrupt request 1 1 the rising edge between two samples of i n tn generates an interrupt request
115 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 15.2.3 eimsk ? external interrupt mask register ? bits 7:0 ? int7:0: external interrupt request 7 - 0 enable w hen an i n t7:0 bit is written to one and the i-bit in the status register (sreg) is set (one), the corresponding external pin interrupt is enabled. the interrupt sense control bits in the external interrupt control registers ? eicra and eicrb ? defines whether the external interrupt is acti- vated on rising or fal ling edge or level sensed. activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. this provides a way of generating a software interrupt. 15.2.4 eifr ? external interrupt flag register ? bits 7:0 ? intf7:0: external interrupt flags 7 - 0 w hen an edge or logic change on the i n t7:0 pin triggers an interrupt request, i n tf7:0 becomes set (one). if the i-bit in sreg and the corresponding interrupt enable bit, i n t7:0 in eimsk, are set (one), the mcu will jump to the interrupt vector . the flag is cleared wh en the interr upt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. these flags are always cleared when i n t7:0 are configured as level interrupt. n ote that when entering sleep mode with the i n t3:0 interrupts disabled, the input buffers on these pins will be disabled. this may cause a logic change in inte rnal signals which will set the i n tf3:0 flags. see ?digital input enable and sleep modes? on page 74 for more information. 15.2.5 pcicr ? pin change interrupt control register ? bit 2 ? pcie2: pin change interrupt enable 1 w hen the pcie2 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 2 is enabled. any change on any enabled pci n t23:16 pin will cause an inter- rupt. the corresponding interrupt of pin change interrupt request is executed from the pci2 interrupt vector. pci n t23:16 pins are enabled individually by the pcmsk2 register. ? bit 1 ? pcie1: pin change interrupt enable 1 w hen the pcie1 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 1 is enabled. any change on any enabled pci n t15:8 pin will cause an inter- rupt. the corresponding interrupt of pin change interrupt request is executed from the pci1 interrupt vector. pci n t15:8 pins are enabled individually by the pcmsk1 register. bit 76543210 0x1d (0x3d) int7 int6 int5 int4 int3 int2 int1 int0 eimsk read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x1c (0x3c) intf7 intf6 intf5 intf4 intf3 intf2 intf1 iintf0 eifr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x68) ? ? ? ? ? pcie2 pcie1 pcie0 pcicr read/ w rite rrrrrr/ w r/ w r/ w initial value00000000
116 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? pcie0: pin change interrupt enable 0 w hen the pcie0 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 0 is enabled. any change on any enabled pci n t7:0 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci0 interrupt vector. pci n t7:0 pins are enabled individually by the pcmsk0 register. 15.2.6 pcifr ? pin change interrupt flag register ? bit 2 ? pcif2: pin change interrupt flag 1 w hen a logic change on any pci n t23:16 pin triggers an interrupt request, pcif2 becomes set (one). if the i-bit in sreg and the pcie2 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alter- natively, the flag can be cleared by writing a logical one to it. ? bit 1 ? pcif1: pin change interrupt flag 1 w hen a logic change on any pci n t15:8 pin triggers an interrupt request, pcif1 becomes set (one). if the i-bit in sreg and the pcie1 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alter- natively, the flag can be cleared by writing a logical one to it. ? bit 0 ? pcif0: pin change interrupt flag 0 w hen a logic change on any pci n t7:0 pin triggers an interrupt request, pcif0 becomes set (one). if the i-bit in sreg and the pcie0 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alter- natively, the flag can be cleared by writing a logical one to it. 15.2.7 pcmsk2 ? pin change mask register 2 ? bit 7:0 ? pcint23:16: pin change enable mask 23:16 each pci n t23:16-bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pci n t23:16 is set and the pcie2 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pci n t23:16 is cleared, pin change interrupt on the corresponding i/o pin is disabled. 15.2.8 pcmsk1 ? pin change mask register 1 bit 76543210 0x1b (0x3b) ? ? ? ? ? pcif2 pcif1 pcif0 pcifr read/ w rite rrrrrr/ w r/ w r/ w initial value00000000 bit 76543210 (0x6d) pcint23 pcint22 pcint21 pcint20 pcint19 pcint18 pcint17 pcint16 pcmsk2 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6c) pcint15 pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 pcmsk1 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
117 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 7:0 ? pcint15:8: pin change enable mask 15:8 each pci n t15:8-bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pci n t15:8 is set and the pcie1 bit in eimsk is set, pin change interrupt is enabled on the corresponding i/o pin. if pci n t15:8 is cleared, pin change interrupt on the corresponding i/o pin is disabled. 15.2.9 pcmsk0 ? pin change mask register 0 ? bit 7:0 ? pcint7:0: pin change enable mask 7:0 each pci n t7:0 bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pci n t7:0 is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the cor- responding i/o pin. if pci n t7:0 is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 (0x6b) pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
118 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16. 8-bit timer/counter0 with pwm 16.1 features ? two independent output compare units ? double buffered outp ut compare registers ? clear timer on compare match (auto reload) ? glitch free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? three independent interrupt sources (tov0, ocf0a, and ocf0b) 16.2 overview timer/counter0 is a general purpose 8-bit time r/counter module, with two independent output compare units, and with p w m support. it allows accurate program execution timing (event man- agement) and wave generation. a simplified block diagram of the 8-bit timer/counter is shown in figure 16-1 . for the actual placement of i/o pins, refer to ?tqfp-pinout atmega640/1280/2560? on page 2 . cpu accessi- ble i/o registers, including i/o bits and i/o pi ns, are shown in bold. the device-specific i/o register and bit locations are listed in the ?register description? on page 129 . figure 16-1. 8-bit timer/counter block diagram 16.2.1 registers the timer/counter (tc n t0) and output compare registers (ocr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req . in the figure) signals are all visible in the timer interrupt flag register (t ifr0). all interrupts are individually masked with the timer inter- rupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. the clock select logic block controls which clock source and edge the timer/counter clock select timer/counter data bus ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb tn edge detector ( from prescaler ) clk tn
119 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare registers (ocr0a and ocr0b) are compared with the timer/counter value at all times. the result of the compare can be used by the w aveform gen- erator to generate a p w m or variable frequency output on the output compare pins (oc0a and oc0b). see ?output compare unit? on page 120. for details. the compare match event will also set the compare flag (ocf0a or ocf0b) which can be used to generate an output compare interrupt request. 16.2.2 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output com- pare unit, in this case compare unit a or compare unit b. howe ver, when using the register or bit defines in a program, the precise form must be used, that is, tc n t0 for accessing timer/counter0 counter value and so on. the definitions in table 16-1 are also used extensively throughout the document. 16.3 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the timer/counter control register (tccr0b). for details on clock sources and pres- caler, see ?timer/counter 0, 1, 3, 4, and 5 prescaler? on page 169 . 16.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 16-2 shows a block diagram of the counter and its surroundings. figure 16-2. counter unit block diagram table 16-1. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is depen- dent on the mode of operation. data b u s tcntn control logic count tovn (int.req.) clock s elect top tn edge detector ( from prescaler ) clk tn bottom direction clear
120 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 signal description (internal signals): count increment or decrement tc n t0 by 1. direction select between increment and decrement. clear clear tc n t0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tc n t0 has reached maximum value. bottom signalize that tc n t0 has reached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). w hen no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tc n t0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the w gm01 and w gm00 bits located in the timer/counter control register (tccr0a) and the w gm02 bit located in the timer/counter control register b (tccr0b). there are clos e connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc0a and oc0b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 123 . the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the w gm02:0 bits. tov0 can be used for generating a cpu interrupt. 16.5 output compare unit the 8-bit comparator continuously compares tc n t0 with the output compare registers (ocr0a and ocr0b). w henever tc n t0 equals ocr0a or ocr0b, the comparator signals a match. a match will set the output compare flag (ocf0a or ocf0 b) at the next timer clock cycle. if the corresponding interrupt is enabled, the output compare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is exe- cuted. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the w aveform generator uses the match signal to generate an output according to operating mode set by the w gm02:0 bits and compare output mode (com0x1:0) bits. the maximum and bottom signals are used by the w aveform generator for handling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 123 ). figure 16-3 on page 121 shows a block diagram of the output compare unit.
121 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 16-3. output compare unit, block diagram the ocr0x registers are double buffered when using any of the pulse w idth modulation (p w m) modes. for the normal and clear timer on compare (ctc) modes of operation, the dou- ble buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical p w m pulses, thereby making the output glitch-free. the ocr0x register access may seem complex, but this is not case. w hen the double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffering is dis- abled the cpu will access the ocr0x directly. 16.5.1 force output compare in non-p w m waveform generation modes, the match output of the comparator can be forced by writing a one to the force outp ut compare (foc0x) bit. forcin g compare match will not set the ocf0x flag or reload/clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the com0x1:0 bits settings de fine whether the oc0x pin is set, cleared or toggled). 16.5.2 compare match bloc king by tcnt0 write all cpu write operations to the tc n t0 register will block any comp are match that occur in the next timer clock cycle, even when the timer is stopped. this feature allows ocr0x to be initial- ized to the same value as tc n t0 without triggering an interrupt when the timer/counter clock is enabled. 16.5.3 using the output compare unit since writing tc n t0 in any mode of operation will blo ck all compare matches for one timer clock cycle, there are risks involved when changing tc n t0 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tc n t0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform ocfn x (int.req.) = ( 8 -bit comparator ) ocrnx ocnx data b u s tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
122 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 generation. similarly, do not write the tc n t0 value equal to bottom when the counter is down-counting. the setup of the oc0x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output com- pare (foc0x) strobe bits in n ormal mode. the oc0x registers keep their values even when changing between w aveform generation modes. be aware that the com0x1:0 bits are not doubl e buffered together with the compare value. changing the com0x1:0 bits will take effect immediately. 16.6 compare match output unit the compare output mode (com0x1:0) bits have two functions. the w aveform generator uses the com0x1:0 bits for defining the output compare (oc0x) state at the next compare match. also, the com0x1:0 bits control the oc0x pin output source. figure 16-4 shows a simplified schematic of the logic affected by the com0x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com0x1:0 bits are shown. w hen referring to the oc0x state, the reference is for the internal oc0x register, not the oc0x pin. if a system reset occur, the oc0x register is reset to ?0?. figure 16-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0x) from the w aveform generator if either of the com0x1:0 bits are set. however, the oc0x pin direction (input or out- put) is still controlled by the da ta direction register (ddr) for th e port pin. the data direction register bit for the oc0x pin (ddr_oc0x) must be set as output before the oc0x value is visi- ble on the pin. the port override function is independent of the w aveform generation mode. the design of the output compare pin logic allows initialization of the oc0x state before the out- put is enabled. n ote that some com0x1:0 bit settings are reserved for certain modes of operation. see ?register description? on page 129 . port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focn clk i/o
123 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16.6.1 compare output mode and waveform generation the w aveform generator uses the com0x1:0 bits differently in n ormal, ctc, and p w m modes. for all modes, setting the com0x1:0 = 0 tells the w aveform generator that no action on the oc0x register is to be performed on the next compare match. for compare output actions in the non-p w m modes refer to table 16-2 on page 129 . for fast p w m mode, refer to table 16-3 on page 129 , and for phase correct p w m refer to table 16-4 on page 130 . a change of the com0x1:0 bits state will have effe ct at the first compare match after the bits are written. for non-p w m modes, the action can be forced to have immediate effect by using the foc0x strobe bits. 16.7 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the w aveform generation mode ( w gm02:0) and compare out- put mode (com0x1:0) bits. the compare output mode bits do not affect the counting sequence, while the w aveform generation mode bits do. the com0x1:0 bits control whether the p w m out- put generated should be inverted or not (inverted or non-inverted p w m). for non-p w m modes the com0x1:0 bits control whether the output should be set, cleared, or toggled at a compare match. see ?compare match output unit? on page 147. for detailed timing information see ?timer/counter timing diagrams? on page 127 . 16.7.1 normal mode the simplest mode of operation is the n ormal mode ( w gm02:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal o peration the timer/counter overflow flag (tov0) will be set in the same timer clock cycle as the tc n t0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the n ormal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in n ormal mode is not recommended, since this will occupy too much of the cpu time. 16.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode ( w gm02:0 = 2), the ocr0a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tc n t0) matches the ocr0a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 16-5 on page 124 . the counter value (tc n t0) increases until a compare match occurs between tc n t0 and ocr0a, and then coun- ter (tc n t0) is cleared.
124 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 16-5. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tc n t0, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com0a1:0 = 1). the oc0a value will not be visible on the port pin unless the data direction for the pin is set to output. the waveform ge nerated will have a ma ximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the n ormal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 16.7.3 fast pwm mode the fast pulse w idth modulation or fast p w m mode ( w gm02:0 = 3 or 7) provides a high fre- quency p w m waveform generation option. the fast p w m differs from the other p w m option by its single-slope operation. the counter counts from bottom to top then restarts from bot- tom. top is defined as 0xff when w gm2:0 = 3, and ocr0a when w gm2:0 = 7. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tc n t0 and ocr0x, and set at bottom. in inverting compare output mode, the out- put is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast p w m mode can be twice as high as the phase correct p w m mode that use dual-slope operation. this high frequency makes the fast p w m mode well suited for power regulation, rectification, and dac app lications. high frequency a llows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast p w m mode, the counter is incremented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast p w m mode is shown in figure 16-6 . the tc n t0 value is in the timing diagram shown as a his- tcntn ocn (toggle) ocnx interrupt flag s et 1 4 period 2 3 (comnx1:0 = 1) f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------- - =
125 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n t0 slopes represent com- pare matches between ocr0x and tc n t0. figure 16-6. fast p w m mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches top. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast p w m mode, the compare unit allows generation of p w m waveforms on the oc0x pins. setting the com0x1:0 bits to tw o will produce a non-inverted p w m and an inverted p w m output can be generated by setting the com0x1:0 to three: setting the com0a1:0 bits to one allows the oc0a pin to toggle on compare matches if the w gm02 bit is set. this option is not available for the oc0b pin (see table 16-3 on page 129 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the p w m waveform is gener- ated by setting (or clearing) the oc0x register at the compare match between ocr0x and tc n t0, and clearing (or setting) the oc0x register at the timer clock cycle the counter is cleared (changes from top to bottom). the p w m frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a p w m waveform output in the fast p w m mode. if the ocr0a is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on the polarity of the output set by the com0a1:0 bits). a frequency (with 50% duty cycle) waveform output in fast p w m mode can be achieved by set- ting oc0x to toggle its logical level on each compare match (com0x1:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this feature is similar to the oc0a toggle in ctc mode, except the double buffer feature of the out- put compare unit is enabled in the fast p w m mode. tcntn ocrnx update and tovn interrupt flag s et 1 period 2 3 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag s et 4 5 6 7 f ocnxpwm f clk_i/o n 256 ? ------------------ =
126 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16.7.4 phase correct pwm mode the phase correct p w m mode ( w gm02:0 = 1 or 5) provides a high resolution phase correct p w m waveform generation option. the phase correct p w m mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bot- tom. top is defined as 0xff when w gm2:0 = 1, and ocr0a when w gm2:0 = 5. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tc n t0 and ocr0x while upcounting, and set on the compare match while down- counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the sym- metric feature of the dual-slope p w m modes, these modes are preferred for motor control applications. in phase correct p w m mode the counter is incremented until the counter value matches top. w hen the counter reaches top, it changes the count direction. the tc n t0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct p w m mode is shown on figure 16-7 . the tc n t0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n t0 slopes represent compare matches between ocr0x and tc n t0. figure 16-7. phase correct p w m mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct p w m mode, the compare unit allows generation of p w m waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted p w m. an inverted p w m output can be generated by setting the com0x1:0 to three: setting the com0a0 bits to one allows the oc0a pin to toggle on compare matches if the w gm02 bit is set. this option is not available for the oc0b pin (see table 16-4 on page 130 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the p w m waveform is tovn interrupt flag s et ocnx interrupt flag s et 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update
127 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 generated by clearing (or setting) the oc0x register at the compare match between ocr0x and tc n t0 when the counter increments, and setting (or clearing) the oc0x register at com- pare match between ocr0x and tc n t0 when the counter decrements. the p w m frequency for the output when using phase correct p w m can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represent special cases when generating a p w m waveform output in the phase correct p w m mode. if the ocr0a is set equal to bottom, the output will be continuously low an d if set equal to max the output will be continuously high for non-inverted p w m mode. for inverted p w m the output will have th e opposite logic values. at the very start of period 2 in figure 16-7 on page 126 ocnx has a transition from high to low even though there is no compare match. the poin t of this transition is to guarantee symmetry around bottom. there are two cases that give a transition without compare match. ? ocr0a changes its value from max, like in figure 16-7 on page 126 . w hen the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match. ? the timer starts counting from a value higher than the one in ocr0a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 16.8 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 16-8 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max va lue in all modes other than phase correct p w m mode. figure 16-8. timer/counter timing diagram, no prescaling figure 16-9 on page 128 shows the same timing data, but with the prescaler enabled. f ocnxpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
128 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 16-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) figure 16-10 shows the setting of ocf0b in all modes and ocf0a in all modes except ctc mode and p w m mode, where ocr0a is top. figure 16-10. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) figure 16-11 shows the setting of ocf0a and the clearing of tc n t0 in ctc mode and fast p w m mode where ocr0a is top. figure 16-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o / 8 ) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o / 8 ) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o / 8 )
129 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16.9 register description 16.9.1 tccr0a ? timer/counter control register a ? bits 7:6 ? com0a1:0: compare match output a mode these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0a pin must be set in order to enable the output driver. w hen oc0a is connected to the pin, the f unction of the com0a1:0 bits depends on the w gm02:0 bit setting. table 16-2 shows the com0a1:0 bit functionality when the w gm02:0 bits are set to a normal or ctc mode (non-p w m). table 16-3 shows the com0a1:0 bit functionality when the w gm01:0 bits are set to fast p w m mode. n ote: 1. a special case occurs when ocr0a equals to p and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at bottom. see ?fast p w m mode? on page 124 for more details. table 16-4 on page 130 shows the com0a1:0 bit functionality when the w gm02:0 bits are set to phase correct p w m mode. bit 7 6 5 4 3 2 1 0 0x24 (0x44) com0a1 com0a0 com0b1 com0b0 ? ? wgm01 wgm00 tccr0a read/ w rite r/ w r/ w r/ w r/ w rrr/ w r/ w initial value 0 0 0 0 0 0 0 0 table 16-2. compare output mode, non-p w m mode com0a1 com0a0 description 00 n ormal port operation, oc0a disconnected 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 16-3. compare output mode, fast p w m mode (1) com0a1 com0a0 description 00 n ormal port operation, oc0a disconnected 01 w gm02 = 0: n ormal port operation, oc0a disconnected w gm02 = 1: toggle oc0a on compare match 10 clear oc0a on compare match, set oc0a at bottom (non-inverting mode) 11 set oc0a on compare match, clear oc0a at bottom (inverting mode)
130 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. a special case occurs when ocr0a equals to p and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct p w m mode? on page 126 for more details. ? bits 5:4 ? com0b1:0: compare match output b mode these bits control the output compare pin (oc0b) behavior. if one or both of the com0b1:0 bits are set, the oc0b output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0b pin must be set in order to enable the output driver. w hen oc0b is connected to the pin, the function of the com0b1:0 bits depends on the w gm02:0 bit setting. table 16-5 shows the com0b1:0 bit functionality when the w gm02:0 bits are set to a normal or ctc mode (non-p w m). table 16-6 shows the com0b1:0 bit functionality when the w gm02:0 bits are set to fast p w m mode. n ote: 1. a special case occurs when ocr0b equals to p and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at bottom. see ?fast p w m mode? on page 124 for more details. table 16-4. compare output mode, phase correct p w m mode (1) com0a1 com0a0 description 00 n ormal port operation, oc0a disconnected 01 w gm02 = 0: n ormal port operation, oc0a disconnected w gm02 = 1: toggle oc0a on compare match 10 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting 11 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting table 16-5. compare output mode, non-p w m mode com0b1 com0b0 description 00 n ormal port operation, oc0b disconnected 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match table 16-6. compare output mode, fast p w m mode (1) com0b1 com0b0 description 00 n ormal port operation, oc0b disconnected 01 reserved 10 clear oc0b on compare match, set oc0b at bottom (non-inverting mode) 11 set oc0b on compare match, clear oc0b at bottom (inverting mode)
131 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 16-7 shows the com0b1:0 bit functionality when the w gm02:0 bits are set to phase cor- rect p w m mode. n ote: 1. a special case occurs when ocr0b equals to p and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct p w m mode? on page 126 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bits 1:0 ? wgm01:0: waveform generation mode combined with the w gm02 bit found in the tccr0b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 16-8 . modes of operation supported by the timer/counter unit are: n ormal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse w idth modulation (p w m) modes (see ?modes of operation? on page 148 ). n ote: 1. max = 0xff 2. bottom = 0x00 table 16-7. compare output mode, phase correct p w m mode (1) com0b1 com0b0 description 00 n ormal port operation, oc0b disconnected 01 reserved 10 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting 11 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting table 16-8. w aveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0000 n ormal 0xff immediate max 1001 p w m, phase correct 0xff top bottom 2010 ctc ocraimmediatemax 3011 fast p w m 0xff top max 4100 reserved ? ? ? 5101 p w m, phase correct ocra top bottom 6110 reserved ? ? ? 7111 fast p w m ocra bottom top
132 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16.9.2 tccr0b ? timer/counter control register b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the w gm bits specify a non-p w m mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in p w m mode. w hen writing a logical one to the foc0a bit, an immediate compare match is forced on the w aveform generation unit. the oc0a output is changed according to its com0a1:0 bits setting. n ote that the foc0a bit is implemented as a strobe. therefore it is the value present in the com0a1:0 bits that determines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6 ? foc0b: force output compare b the foc0b bit is only active when the w gm bits specify a non-p w m mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in p w m mode. w hen writing a logical one to the foc0b bit, an immediate compare match is forced on the w aveform generation unit. the oc0b output is changed according to its com0b1:0 bits setting. n ote that the foc0b bit is implemented as a strobe. therefore it is the value present in the com0b1:0 bits that determines the effect of the forced compare. a foc0b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 3 ? wgm02: waveform generation mode see the description in the ?tccr0a ? timer/counter control register a? on page 129 . ? bits 2:0 ? cs02:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see table 16-9 on page 133 . bit 7 6 5 4 3 2 1 0 0x25 (0x45) foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/ w rite ww rrr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
133 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 16.9.3 tcnt0 ? timer/counter register the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. w riting to the tc n t0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tc n t0) while the counter is running, introduces a risk of missing a compare match between tc n t0 and the ocr0x registers. 16.9.4 ocr0a ? output compare register a the output compare register a contains an 8-bi t value that is continuously compared with the counter value (tc n t0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. 16.9.5 ocr0b ? output compare register b the output compare register b contains an 8-bi t value that is continuously compared with the counter value (tc n t0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0b pin. table 16-9. clock select bit description cs02 cs01 cs00 description 000 n o clock source (timer/counter stopped) 001 clk i/o /( n o prescaling) 010 clk i/o /8 (from prescaler) 011 clk i/o /64 (from prescaler) 100 clk i/o /256 (from prescaler) 101 clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge 1 1 1 external clock source on t0 pin. clock on rising edge bit 76543210 0x26 (0x46) tcnt0[7:0] tcnt0 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x27 (0x47) ocr0a[7:0] ocr0a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 0x28 (0x48) ocr0b[7:0] ocr0b read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
134 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 16.9.6 timsk0 ? timer/counter interrupt mask register ? bits 7:3, 0 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 2 ? ocie0b: timer/counter output compare match b interrupt enable w hen the ocie0b bit is written to one, and the i-bit in the status register is set, the timer/counter compare match b interrupt is enab led. the corresponding interrupt is executed if a compare match in timer/counter occurs, that is, when the ocf0b bit is set in the timer/counter interrupt flag register ? tifr0. ? bit 1 ? ocie0a: timer/counter0 output compare match a interrupt enable w hen the ocie0a bit is written to one, and the i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, that is, when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable w hen the toie0 bit is written to one, and the i-bit in the status register is set, the timer/counter0 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter0 occurs, that is, when the tov0 bit is set in the timer/counter 0 inter- rupt flag register ? tifr0. 16.9.7 tifr0 ? timer/counter 0 interrupt flag register ? bits 7:3, 0 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 2 ? ocf0b: timer/counter 0 output compare b match flag the ocf0b bit is set when a compare match occurs between the timer/counter and the data in ocr0b ? output compare register0 b. ocf0b is cleared by hardware when executing the cor- responding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. w hen the i-bit in sreg, ocie0b (timer/counter compare b match interrupt enable), and ocf0b are set, the timer/counter compare match interrupt is executed. ? bit 1 ? ocf0a: timer/counter 0 output compare a match flag the ocf0a bit is set when a compare match occurs between the timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when executing the cor- responding interrupt handling vector. alternativel y, ocf0a is cleared by writing a logic one to the flag. w hen the i-bit in sreg, ocie0a (timer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 compare match interrupt is executed. bit 76543 2 10 (0x6e) ? ? ? ? ? ocie0b ocie0a toie0 timsk0 read/ w rite rrrrrr/ w r/ w r/ w initial value00000 0 00 bit 76543210 0x15 (0x35) ?????ocf0bocf0a tov0 tifr0 read/ w rite rrrrrr/ w r/ w r/ w initial value00000000
135 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occurs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. w hen the sreg i-bit, toie0 (timer/counter0 overflow interrupt enable), and tov0 are set, the timer/counter0 overflow interrupt is executed. the setting of this flag is dependent of the w gm02:0 bit setting. refer to table 16-8 , ? w aveform generation mode bit description? on page 131 .
136 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17. 16-bit timer/counter (timer/counter 1, 3, 4, and 5) 17.1 features ? true 16-bit design (that is, allows 16-bit pwm) ? three independent output compare units ? double buffered outp ut compare registers ? one input capture unit ? input capture noise canceler ? clear timer on compare match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? twenty independent interrupt sources (tov1, ocf1a, ocf1b, ocf1c, icf1, tov3, ocf3a, ocf3b, ocf3c, icf3, tov4, ocf4a, ocf4b, ocf4c, icf4, tov5, ocf5a, ocf5b, ocf5c and icf5) 17.2 overview the 16-bit timer/counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. most register and bit references in this sect ion are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output compare unit channel. however, when using the register or bit defines in a program, the precise form must be used, that is, tc n t1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit timer/counter is shown in figure 17-1 on page 137 . for the actual placement of i/o pins, see ?tqfp-pinout atmega640/1280/2560? on page 2 and ?pinout atmega1281/2561? on page 4 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i /o register and bit locations are listed in the ?reg- ister description? on page 158 . the power reduction timer/counter1 bit, prtim1, in ?prr0 ? power reduction register 0? on page 56 must be written to zero to enable timer/counter1 module. the power reduction timer/counter3 bit, prtim3, in ?prr1 ? power reduction register 1? on page 57 must be written to zero to enable timer/counter3 module. the power reduction timer/counter4 bit, prtim4, in ?prr1 ? power reduction register 1? on page 57 must be written to zero to enable timer/counter4 module. the power reduction timer/counter5 bit, prtim5, in ?prr1 ? power reduction register 1? on page 57 must be written to zero to enable timer/counter5 module. timer/counter4 and timer/counter5 only have full functionality in the atmega640/1280/2560. input capture and output compare are not available in the atmega1281/2561.
137 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 17-1. 16-bit timer/counter block diagram (1) n ote: 1. refer to figure 1-1 on page 2 , table 13-5 on page 79 , and table 13-11 on page 83 for timer/counter1 and 3 and 3 pin placement and description. 17.2.1 registers the timer/counter (tc n tn), output compare registers (ocrna/b/c), and input capture reg- ister (icrn) are all 16-bit registers. special procedures must be followed when accessing the 16- bit registers. these procedures are described in the section ?accessing 16-bit registers? on page 138 . the timer/counter control registers (t ccrna/b/c) are 8-bit registers and have no cpu access restrictions. interrupt requests (short en as int.req.) signals are all visible in the timer interrupt flag register (t ifrn). all interrupts are individually masked with the timer inter- rupt mask register (timskn). tifrn and timskn are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the tn pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t n ). the double buffered output compare registers (ocrna/b/c) are compared with the timer/counter value at all time. the result of the compare can be used by the w aveform gener- ator to generate a p w m or variable frequency output on the output compare pin (ocna/b/c). icfn (int.req.) tovn (int.req.) clock select timer/counter databus icrn = = = tcntn waveform generation waveform generation waveform generation ocna ocnb ocnc noise canceler icpn = fixed top values edge detector control logic = 0 top bottom count clear direction ocfna (int.req.) ocfnb (int.req.) ocfnc (int.req.) tccrna tccrnb tccrnc ( from analog comparator ouput ) tn edge detector ( from prescaler ) tclk ocrnc ocrnb ocrna
138 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 see ?output compare units? on page 145. the compare match event will also set the compare match flag (ocfna/b/c) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/ counter value at a given external (edge trig- gered) event on either the input capture pin (icpn) or on the analog comparator pins (see ?ac ? analog comparator? on page 271 ). the input capture unit incl udes a digital filtering unit ( n oise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocrna register, the icrn register, or by a set of fixed values. w hen using ocrna as top value in a p w m mode, the ocrna register can not be used for generating a p w m output. however, the top va lue will in this case be doub le buffered allowing the top value to be changed in run time. if a fixed top value is required, the icrn register can be used as an alternative, freeing the ocrna to be used as p w m output. 17.2.2 definitions the following definitions are used extensively throughout the document: 17.3 accessing 16-bit registers the tc n tn, ocrna/b/c, and icrn are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write opera- tions. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16- bit access. the same temporary register is shared between all 16-bit registers within each 16- bit timer. accessing the low byte triggers the 16-bit read or write operation. w hen the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. w hen the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. n ot all 16-bit accesses uses the temporary regi ster for the high byte. reading the ocrna/b/c 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte. for a 16-bit read, the low byte must be read before the high byte. the following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocrna/b/c and icrn registers. n ote that when using ?c?, the compiler handles the 16-bit access. table 17-1. definitions bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocrna or icrn reg- ister. the assignment is dependent of the mode of operation.
139 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. the assembly code example returns the tc n tn value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer regis- ters, then the result of the a ccess outside the interrupt will be corrupted. theref ore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tc n tn register contents. reading any of the ocrna/b/c or icrn registers can be done by using the same principle. assembly code examples (1) ... ; set tcntn to 0x01ff ldi r17,0x01 ldi r16,0xff out tcntnh,r17 out tcntnl,r16 ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ... c code examples (1) unsigned int i; ... /* set tcntn to 0x01ff */ tcntn = 0x1ff; /* read tcntn into i */ i = tcntn; ...
140 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. the assembly code example returns the tc n tn value in the r17:r16 register pair. assembly code example (1) tim16_readtcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcntn into r17:r16 in r16,tcntnl in r17,tcntnh ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcntn( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* read tcntn into i */ i = tcntn; /* restore global interrupt flag */ sreg = sreg; return i; }
141 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the following code examples show how to do an atomic write of the tc n tn register contents. w riting any of the ocrna/b/c or icrn registers can be done by using the same principle. n ote: 1. see ?about code examples? on page 11. the assembly code example requires that the r17:r16 register pair contains the value to be writ- ten to tc n tn. 17.3.1 reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. 17.4 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (csn2:0) bits located in the timer/counter control register b (tccrnb). for details on clock sources and prescaler, see ?timer/counter 0, 1, 3, 4, and 5 prescaler? on page 169 . assembly code example (1) tim16_writetcntn: ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcntn to r17:r16 out tcntnh,r17 out tcntnl,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcntn( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* set tcntn to i */ tcntn = i; /* restore global interrupt flag */ sreg = sreg; }
142 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.5 counter unit the main part of the 16-bit timer/counter is th e programmable 16-bit bi-directional counter unit. figure 17-2 shows a block diagram of the counter and its surroundings. figure 17-2. counter unit block diagram signal description (internal signals): count increment or decrement tc n tn by 1. direction select between increment and decrement. clear clear tc n tn (set all bits to zero). clk t n timer/counter clock. top signalize that tc n tn has reached maximum value. bottom signalize that tc n tn has reached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tc n tnh) con- taining the upper eight bits of the counter, and counter low (tc n tnl) containing the lower eight bits. the tc n tnh register can only be indirectly accessed by the cpu. w hen the cpu does an access to the tc n tnh i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tc n tnh value when the tc n tnl is read, and tc n tnh is updated with the temporary register value when tc n tnl is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are special cases of writing to the tc n tn register when the counter is counting that will gi ve unpredictable results. the s pecial cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t n ). the clk t n can be generated from an external or internal clock source, selected by the clock select bits (csn2:0). w hen no clock source is selected (csn2:0 = 0) the timer is stopped. however, the tc n tn value can be accessed by the cpu, independent of whether clk t n is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits ( w gmn3:0) located in the timer/counter control registers a and b (tccrna and tccrnb). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs ocnx. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 148 . the timer/counter overflow flag (tovn) is set according to the mode of operation selected by the w gmn3:0 bits. tovn can be used for generating a cpu interrupt. temp ( 8 -bit) data b u s ( 8 -bit) tcntn (16-bit counter) tcntnh ( 8 -bit) tcntnl ( 8 -bit) control logic count clear direction tovn (int.req.) clock s elect top bottom tn edge detector ( from prescaler ) clk tn
143 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.6 input capture unit the timer/counter incorporates an input capture un it that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or mul- tiple events, can be applied via the icpn pin or al ternatively, for the timer/counter1 only, via the analog comparator unit. the time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 17-3 . the elements of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 17-3. input capture unit block diagram n ote: the analog comparator output (aco) can only trigger the timer/counter1 icp ? not timer/counter3, 4 or 5. w hen a change of the logic level (an event) occurs on the input capture pin (icpn), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a capture will be triggered. w hen a capture is triggered, the 16-bit value of the counter (tc n tn) is written to the input capture register (icrn). the input capture flag (icfn) is set at the same system clock as the tc n tn value is copied into icrn register. if enabled (ticien = 1), the input capture flag generates an input capt ure interrupt. the icfn flag is automatically cleared when the interrupt is executed. alternativ ely the icfn flag can be cleared by software by writing a logical one to its i/o bit location. reading the 16-bit value in the input capture register (icrn) is done by first reading the low byte (icrnl) and then the high byte (icrnh). w hen the low byte is read the high byte is copied into the high byte temporary register (temp). w hen the cpu reads the icrnh i/o location it will access the temp register. icfn (int.req.) analog comparator write icrn (16-bit register) icrnh ( 8 -bit) noise canceler icpn edge detector temp ( 8 -bit) data b u s ( 8 -bit) icrnl ( 8 -bit) tcntn (16-bit counter) tcntnh ( 8 -bit) tcntnl ( 8 -bit) acic* icnc ices aco*
144 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the icrn register can only be written when using a w aveform generation mode that utilizes the icrn register for defining the counter?s top value. in these cases the waveform genera- tion mode ( w gmn3:0) bits must be set before the top value can be written to the icrn register. w hen writing the icrn register the high byte must be written to the icrnh i/o location before the low byte is written to icrnl. for more information on how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 138 . 17.6.1 input capture trigger source the main trigger source for the input capture unit is the input capture pin (icpn). timer/counter1 can alternatively use the analog comparator output as trigger source for the input capture unit. the analog comparator is selected as trigger source by setting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a capture. the input capture flag must therefore be cleared after the change. both the input capture pin (icpn) and the analog comparator output (aco) inputs are sampled using the same technique as for the tn pin ( figure 18-1 on page 169 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. n ote that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a w ave- form generation mode that uses icrn to define top. an input capture can be tri ggered by software by controllin g the port of the icpn pin. 17.6.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (ic n cn) bit in timer/counter control register b (tccrnb). w hen enabled the noise canceler introduces addi- tional four system clock cycles of delay from a change applied to the input, to the update of the icrn register. the noise canceler uses the sy stem clock and is therefore not affected by the prescaler. 17.6.3 using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in th e icrn register before the nex t event occurs, the icrn will be overwritten with a new value. in this case the result of the ca pture will be incorrect. w hen using the input capture interrupt, the icrn register should be read as early in the inter- rupt handler routine as possible. even though the input capture interrupt has relatively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icrn
145 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 register has been read. after a change of the edge, the input capture flag (icfn) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icfn flag is not required (if an interrupt handler is used). 17.7 output compare units the 16-bit comparator continuously compares tc n tn with the output compare register (ocrnx). if tc n t equals ocrnx the comparator signals a match. a match will set the output compare flag (ocfnx) at the next timer clock cycle. if enabled (ocienx = 1), the output com- pare flag generates an output compare interrupt. the ocfnx flag is automatically cleared when the interrupt is executed. alternatively the ocfnx flag can be cleared by software by writ- ing a logical one to its i/o bit location. the w aveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode ( w gmn3:0) bits and compare output mode (comnx1:0) bits. the top and bottom signals are used by the w aveform generator for handling the special cases of the extreme values in some modes of operation. see ?modes of operation? on page 148. a special feature of output compare unit a allows it to define the timer/counter top value (that is, counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the w aveform generator. figure 17-4 shows a block diagram of the output compare unit. the small ?n? in the register and bit names indicates the device number (n = n for timer/counter n), and the ?x? indicates output compare unit (a/b/c). the elements of the block diagram that are not directly a part of the out- put compare unit are gray shaded. figure 17-4. output compare unit, block diagram ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. ( 8 -bit) ocnx temp ( 8 -bit) data b u s ( 8 -bit) ocrnxl buf. ( 8 -bit) tcntn (16-bit counter) tcntnh ( 8 -bit) tcntnl ( 8 -bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh ( 8 -bit) ocrnxl ( 8 -bit) waveform generator top bottom
146 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the ocrnx register is double buffered when using any of the twelve pulse width modulation (p w m) modes. for the n ormal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocrnx com- pare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical p w m pulses, thereby making the out- put glitch-free. the ocrnx register access may seem complex, but this is not case. w hen the double buffering is enabled, the cpu has access to the ocrnx buffer register, and if double buffering is dis- abled the cpu will access the ocrnx directly. the content of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as the tc n t1 and icr1 register). therefore ocr1x is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as when accessing other 16-bit registers. w riting the ocrnx registers must be done via the temp reg- ister since the compare of all 16 bits is done continuously. the high byte (ocrnxh) has to be written first. w hen the high byte i/o location is written by the cpu, the temp register will be updated by the value written. then when the low by te (ocrnxl) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the ocrnx bu ffer or ocrnx compare register in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 138 . 17.7.1 force output compare in non-p w m w aveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (focnx) bit. forcing compare match will not set the ocfnx flag or reload/clear the timer, but the ocnx pin will be updated as if a real compare match had occurred (the comn1:0 bits settings define whether the ocnx pin is set, cleared or toggled). 17.7.2 compare match bloc king by tcntn write all cpu writes to the tc n tn register will block any compare ma tch that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocrnx to be initialized to the same value as tc n tn without triggering an interrupt when the timer/counter clock is enabled. 17.7.3 using the output compare unit since writing tc n tn in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tc n tn when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tc n tn equals the ocrnx value, the compare match will be missed, resulti ng in incorrect wave- form generation. do not write the tc n tn equal to top in p w m modes with variable top values. the compare match for the top will be ignored and the counte r will continue to 0xffff. similarly, do not write the tc n tn value equal to bottom when the counter is downcounting. the setup of the ocnx should be performed before setting the data direction register for the port pin to output. the easiest way of setting the ocnx value is to use the force output com- pare (focnx) strobe bits in n ormal mode. the ocnx register keeps its value even when changing between w aveform generation modes. be aware that the comnx1:0 bits are not doubl e buffered together with the compare value. changing the comnx1:0 bits will take effect immediately.
147 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.8 compare match output unit the compare output mode (comnx1:0) bits have two functions. the w aveform generator uses the comnx1:0 bits for defining the output compare (ocnx) state at the next compare match. secondly the comnx1:0 bits control the ocnx pin output source. figure 17-5 shows a simplified schematic of the logic affected by the comnx1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the comnx1:0 bits are shown. w hen referring to the ocnx state, the reference is for the internal ocnx register, not the ocnx pin. if a system reset occur, the ocnx register is reset to ?0?. figure 17-5. compare match output unit, schematic the general i/o port function is overridden by the output compare (ocnx) from the w aveform generator if either of the comnx1:0 bits are set. however, the ocnx pin direction (input or out- put) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the ocnx pin (ddr_ocnx) must be set as output before the ocnx value is visi- ble on the pin. the port override func tion is generally independent of the w aveform generation mode, but there are some exceptions. refer to table 17-3 on page 159 , table 17-4 on page 159 and table 17-5 on page 160 for details. the design of the output compare pin logic allows initialization of the ocnx state before the out- put is enabled. n ote that some comnx1:0 bit settings are reserved for certain modes of operation. see ?register description? on page 158. the comnx1:0 bits have no effect on the input capture unit. 17.8.1 compare output mode and waveform generation the w aveform generator uses the comnx1:0 bits differently in normal, ctc, and p w m modes. for all modes, setting the comnx1:0 = 0 tells the w aveform generator that no action on the ocnx register is to be performed on the next compare match. for compare output actions in the port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
148 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 non-p w m modes refer to table 17-3 on page 159 . for fast p w m mode refer to table 17-4 on page 159 , and for phase correct and phase and frequency correct p w m refer to table 17-5 on page 160 . a change of the comnx1:0 bits st ate will have effect at the first compare match after the bits are written. for non-p w m modes, the action can be forced to have immediate effect by using the focnx strobe bits. 17.9 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode ( w gmn3:0) and compare out- put mode (comnx1:0) bits. the compare output mode bits do not affect the counting sequence, while the w aveform generation mode bits do. the comnx1:0 bits control whether the p w m out- put generated should be inverted or not (inverted or non-inverted p w m). for non-p w m modes the comnx1:0 bits control whether the output should be set, cleared or toggle at a compare match. see ?compare match output unit? on page 147. n ote: 1. the ctcn and p w mn1:0 bit definition names are obsolete. use the w gmn2:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. for detailed timing information refer to ?timer/counter timing diagrams? on page 156 . table 17-2. w aveform generation mode bit description (1) mode wgmn3 wgmn2 (ctcn) wgmn1 (pwmn1) wgmn0 (pwmn0) timer/counter mode of operation top update of ocrn x at tovn flag set on 00 0 0 0 n ormal 0xffff immediate max 10 0 0 1p w m, phase correct, 8-bit 0x00ff top bottom 20 0 1 0p w m, phase correct, 9-bit 0x01ff top bottom 30 0 1 1p w m, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocrna immediate max 50 1 0 1 fast p w m, 8-bit 0x00ff bottom top 60 1 1 0 fast p w m, 9-bit 0x01ff bottom top 70 1 1 1 fast p w m, 10-bit 0x03ff bottom top 81 0 0 0 p w m, phase and frequency correct icrn bottom bottom 91 0 0 1 p w m,phase and frequency correct ocrna bottom bottom 101010p w m, phase correct icrn top bottom 111011p w m, phase correct ocrna top bottom 12 1 1 0 0 ctc icrn immediate max 131101 (reserved) ? ? ? 141110 fast p w micrnbottomtop 151111 fast p w m ocrna bottom top
149 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.9.1 normal mode the simplest mode of operation is the normal mode ( w gmn3:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter overflow flag (tovn) will be set in the same timer clock cycle as the tc n tn becomes zero. the tovn flag in this case behaves like a 17 th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tovn flag, the timer resolution can be increased by soft- ware. there are no special cases to consider in the n ormal mode, a new counter value can be written anytime. the input capture unit is easy to use in n ormal mode. however, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generat e interrupts at some given time. using the output compare to generate waveforms in n ormal mode is not recommended, since this will occupy too much of the cpu time. 17.9.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode ( w gmn3:0 = 4 or 12), the ocrna or icrn register are used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tc n tn) matches either the ocrna ( w gmn3:0 = 4) or the icrn ( w gmn3:0 = 12). the ocrna or icrn define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the opera- tion of counting external events. the timing diagram for the ctc mode is shown in figure 17-6 . the counter value (tc n tn) increases until a compare match occurs with either ocrna or icrn, and then counter (tc n tn) is cleared. figure 17-6. ctc mode, timing diagram an interrupt can be generated at each time the counter value reaches the top value by either using the ocfna or icfn flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. how- ever, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buff- ering feature. if the new value written to ocrna or icrn is lower than the current value of tcntn ocna (toggle) ocna interrupt flag s et or icfn interrupt flag s et (interrupt on top) 1 4 period 2 3 (comna1:0 = 1)
150 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 tc n tn, the counter will miss the compare match. the counter will then have to count to its max- imum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desirable. an al ternative will then be to use the fast p w m mode using ocrna for defining top ( w gmn3:0 = 15) since the ocrna then will be doub le buffered. for generating a waveform output in ctc mode, the ocna output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (comna1:0 = 1). the ocna value will not be visible on the port pin unless the data direction for the pin is set to output (ddr_ocna = 1). th e waveform generated will have a maximum fre- quency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the n ormal mode of operation, the tovn flag is set in the same timer clock cycle that the counter counts from max to 0x0000. 17.9.3 fast pwm mode the fast pulse width modulation or fast p w m mode ( w gmn3:0 = 5, 6, 7, 14, or 15) provides a high frequency p w m waveform generation option. the fast p w m differs from the other p w m options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tc n tn and ocrnx, and set at bottom. in inverting compare output mode output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast p w m mode can be twice as high as the phase cor- rect and phase and frequency correct p w m modes that use dual-slope operation. this high frequency makes the fast p w m mode well suited for power regu lation, rectification, and dac applications. high frequency allows physically sm all sized external com ponents (coils, capaci- tors), hence reduces total system cost. the p w m resolution for fast p w m can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the p w m resolution in bits can be calculated by using the following equation: in fast p w m mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff ( w gmn3:0 = 5, 6, or 7), the value in icrn ( w gmn3:0 = 14), or the value in ocrna ( w gmn3:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast p w m mode is shown in figure 17-7 on page 151 . the figure shows fast p w m mode when ocrna or icrn is used to define top. the tc n tn value is in the timing diagram shown as a hist ogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n tn slopes represent compare matches between ocrnx and tc n tn. the ocnx interrupt flag will be set when a compare match occurs. f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------- - = r fpwm top 1 + () log 2 () log ---------------------------------- - =
151 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 17-7. fast p w m mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches top. in addition the ocna or icfn flag is set at the same time r clock cycle as tovn is set when either ocrna or icrn is used for defining the top value. if one of the interrupts are enabled, the interrupt han- dler routine can be used for updating the top and compare values. w hen changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tc n tn and the ocrnx. n ote that when using fixed top values the unused bits are masked to zero when any of the ocrnx registers are written. the procedure for updating icrn differs from updating ocrna when used for defining the top value. the icrn register is not double buffered. this means that if icrn is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icrn value written is lower than the current value of tc n tn. the result will then be that the counter will miss the compare matc h at the top value. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. the ocrna register however, is double buffered. this feature allows the ocrna i/o location to be written anytime. w hen the ocrna i/o location is written the value written will be put into the ocrna buffer register. th e ocrna compare register will th en be updated with the value in the buffer register at the next timer clock cycle the tc n tn matches top. the update is done at the same timer clock cycle as the tc n tn is cleared and the tovn flag is set. using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a p w m output on ocna. however, if the base p w m frequency is actively changed (by ch anging the top value), using the ocrna as top is clearly a better choice due to its double buffer feature. in fast p w m mode, the compare units allow generation of p w m waveforms on the ocnx pins. setting the comnx1:0 bits to tw o will produce a non-inverted p w m and an inverted p w m output can be generated by setting the comnx1:0 to three (see table on page 159 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the p w m waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tc n tn, and clearing (or setting) the ocnx register at the timer clock cycle the counter is cleared (changes from top to bottom). tcntn ocrnx / top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
152 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the p w m frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represents special cases when generating a p w m waveform output in the fast p w m mode. if the ocrnx is set equal to bottom (0x0000) the out- put will be a narrow spike for eac h top+1 timer clock cycle. se tting the ocrnx equal to top will result in a const ant high or low output (depending on the polarity of the output set by the comnx1:0 bits). a frequency (with 50% duty cycle) waveform output in fast p w m mode can be achieved by set- ting ocna to toggle its logical level on each compare match (comna1:0 = 1). this applies only if ocr1a is used to define the top value ( w gm13:0 = 15). the wave form generated will have a maximum frequency of f oc n a = f clk_i/o /2 when ocrna is set to zero (0x0000). this feature is similar to the ocna toggle in ctc mode, except the double buffer feature of the output com- pare unit is enabled in the fast p w m mode. 17.9.4 phase correct pwm mode the phase correct pulse width modulation or phase correct p w m mode ( w gmn3:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct p w m waveform generation option. the phase correct p w m mode is, like the phase and frequency correct p w m mode, based on a dual- slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tc n tn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope p w m modes, these modes are preferred for motor control applications. the p w m resolution for the phase correct p w m mode can be fixed to 8-bit, 9-bit, or 10-bit, or defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the p w m reso- lution in bits can be calculated by using the following equation: in phase correct p w m mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff ( w gmn3:0 = 1, 2, or 3), the value in icrn ( w gmn3:0 = 10), or the value in ocrna ( w gmn3:0 = 11). the counter has then reached the top and changes the count direction. the tc n tn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct p w m mode is shown on figure 17-8 on page 153 . the figure shows phase correct p w m mode when ocrna or icrn is used to define top. the tc n tn value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n tn slopes represent compare matches between ocrnx and tc n tn. the ocnx interrupt flag will be set when a compare match occurs. f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- - = r pcpwm top 1 + () log 2 () log ---------------------------------- - =
153 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 17-8. phase correct p w m mode, timing diagram the timer/counter overflow flag (tovn) is set each time the counter reaches bottom. w hen either ocrna or icrn is used for defining the top value, the ocna or icfn flag is set accord- ingly at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. w hen changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tc n tn and the ocrnx. n ote that when using fixed top values, the unused bits are masked to zero when any of the ocrnx registers are written. as the third period shown in figure 17-8 illustrates, changing the top actively while the timer/counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocrnx reg- ister. since the ocrnx update occurs at top, the p w m period starts and ends at top. this implies that the length of the falling slope is determined by the previous top value, while the length of the rising slope is determined by the new top value. w hen these two values differ the two slopes of the period will differ in length. the difference in length gives the unsymmetrical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the timer/counter is running. w hen using a static top value there are practically no differences between the two modes of operation. in phase correct p w m mode, the compare units allow generation of p w m waveforms on the ocnx pins. setting the comnx1:0 bits to two will produce a non-inverted p w m and an inverted p w m output can be generated by setting the comnx1:0 to three (see table 17-5 on page 160 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the p w m waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tc n tn when the counter increments, and clearing (or setting) the ocnx register at compare match between ocrnx and tc n tn when ocrnx/top update and ocna interrupt flag s et or icfn interrupt flag s et (interrupt on top) 1 2 3 4 tovn interrupt flag s et (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
154 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the counter decrements. the p w m frequency for the output when using phase correct p w m can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocrnx register represent special cases when generating a p w m waveform output in the phase correct p w m mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted p w m mode. for inverted p w m the output will have the opposite logic values. if ocr1a is used to define the top value ( w gm13:0 = 11) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 17.9.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct p w m mode ( w gmn3:0 = 8 or 9) provides a high resolution phase and frequency correct p w m wave- form generation option. the phase and frequency correct p w m mode is, like the phase correct p w m mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (ocnx) is cleared on the compare match between tc n tn and ocrnx while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation fre- quency compared to the single-slope operation. howe ver, due to the symmetric feature of the dual-slope p w m modes, these modes are preferred for motor control applications. the main difference between the phase correct, and the phase and frequency correct p w m mode is the time the ocrnx register is updated by the ocrnx buffer register, see figure 17-8 on page 153 and figure 17-9 on page 155 . the p w m resolution for the phase and frequency correct p w m mode can be defined by either icrn or ocrna. the minimum resolution allowed is 2-bit (icrn or ocrna set to 0x0003), and the maximum resolution is 16-bit (icrn or ocrna set to max). the p w m resolution in bits can be calculated using the following equation: in phase and frequency correct p w m mode the counter is incremented until the counter value matches either the value in icrn ( w gmn3:0 = 8), or the value in ocrna ( w gmn3:0 = 9). the counter has then reached the top and changes the count direction. the tc n tn value will be equal to top for one timer clock cycle. the timing diagram for the phase correct and frequency correct p w m mode is shown on figure 17-9 on page 155 . the figure shows phase and fre- quency correct p w m mode when ocrna or icrn is used to define top. the tc n tn value is in the timing diagram shown as a histogram for il lustrating the dual-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n tn slopes represent compare matches between ocrnx and tc n tn. the ocnx interrupt flag will be set when a compare match occurs. f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - = r pfcpwm top 1 + () log 2 () log ---------------------------------- - =
155 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 17-9. phase and frequency correct p w m mode, timing diagram the timer/counter overflow flag (tovn) is set at the same timer clock cycle as the ocrnx registers are updated with the double buffer value (at bottom). w hen either ocrna or icrn is used for defining the top value, the ocna or icfn flag set when tc n tn has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. w hen changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare ma tch will never occur between the tc n tn and the ocrnx. as figure 17-9 shows the output generated is, in contrast to the phase correct mode, symmetri- cal in all periods. since the ocrnx registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. using the icrn register for defining top work s well when using fixed top values. by using icrn, the ocrna register is free to be used for generating a p w m output on ocna. however, if the base p w m frequency is actively changed by changing the top value, using the ocrna as top is clearly a better choice due to its double buffer feature. in phase and frequency correct p w m mode, the compare units allow generation of p w m wave- forms on the ocnx pins. setting the comnx1:0 bits to two will produce a non-inverted p w m and an inverted p w m output can be generated by setting the comnx1:0 to three (see table 17-5 on page 160 ). the actual ocnx value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_ocnx). the p w m waveform is generated by setting (or clearing) the ocnx register at the compare match between ocrnx and tc n tn when the counter incre- ments, and clearing (or setting) the ocnx register at compare match between ocrnx and tc n tn when the counter decrements. the p w m frequency for the output when using phase and frequency correct p w m can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). ocrnx/top updateand tovn interrupt flag s et (interrupt on bottom) ocna interrupt flag s et or icfn interrupt flag s et (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - =
156 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the extreme values for the ocrnx register represents special cases when generating a p w m waveform output in the phase correct p w m mode. if the ocrnx is set equal to bottom the output will be continuously low and if set equal to top the output will be set to high for non- inverted p w m mode. for inverted p w m the output will have the opposite logic values. if ocr1a is used to define the top value ( w gm13:0 = 9) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 17.10 timer/counte r timing diagrams the timer/counter is a synchronous design and the timer clock (clk tn ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set, and when the ocrnx register is updated with the ocrnx buffer value (only for modes utilizing double buffering). figure 17-10 shows a timing diagram for the setting of ocfnx. figure 17-10. timer/counter timing diagram, setting of ocfnx, no prescaling figure 17-11 shows the same timing data, but with the prescaler enabled. figure 17-11. timer/counter timing diagram, setting of ocfnx, with prescaler (f clk_i/o /8) clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o / 8 )
157 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 17-12 shows the count sequence clos e to top in various modes. w hen using phase and frequency correct p w m mode the ocrnx register is updated at bottom. the timing diagrams will be the same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tovn flag at bottom. figure 17-12. timer/counter timing diagram, no prescaling figure 17-13 shows the same timing data, but with the prescaler enabled. figure 17-13. timer/counter timing dia gram, with prescaler (f clk_i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o tovn (fpwm) and icf n (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o / 8 )
158 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.11 register description 17.11.1 tccr1a ? timer/counter 1 control register a 17.11.2 tccr3a ? timer/counter 3 control register a 17.11.3 tccr4a ? timer/counter 4 control register a 17.11.4 tccr5a ? timer/counter 5 control register a ? bit 7:6 ? comna1:0: compare output mode for channel a ? bit 5:4 ? comnb1:0: compare output mode for channel b ? bit 3:2 ? comnc1:0: compare output mode for channel c the comna1:0, comnb1:0, and comnc1:0 control the output compare pins (ocna, ocnb, and ocnc respectively) behavior. if one or both of the comna1:0 bits are written to one, the ocna output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the comnb1:0 bits are written to one, the ocnb output overrides the normal port func- tionality of the i/o pin it is connected to. if one or both of the comnc1:0 bits are written to one, the ocnc output overrides the normal port functionality of the i/o pin it is connected to. how- ever, note that the data direction register (ddr) bit corresponding to the ocna, ocnb or ocnc pin must be set in order to enable the output driver. w hen the ocna, ocnb or ocnc is connected to the pin, the function of the comnx1:0 bits is dependent of the w gmn3:0 bits setting. table 17-3 on page 159 shows the comnx1:0 bit func- tionality when the w gmn3:0 bits are set to a normal or a ctc mode (non-p w m). bit 76543210 (0x80) com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 wgm11 wgm10 tccr1a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x90) com3a1 com3a0 com3b1 com3b0 com3c1 com3c0 wgm31 wgm30 tccr3a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0xa0) com4a1 com4a0 com4b1 com4b0 com4c1 com4c0 wgm41 wgm40 tccr4a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x120) com5a1 com5a0 com5b1 com5b0 com5c1 com5c0 wgm51 wgm50 tccr5a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
159 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 1:0 ? wgmn1:0: waveform generation mode combined with the w gmn3:2 bits found in the tccrnb register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 17-2 on page 148 . modes of operation supported by the timer/counter unit are: n ormal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse w idth modulation (p w m) modes. for more information on the different modes, see ?modes of operation? on page 148 . table 17-4 shows the comnx1:0 bit functionality when the w gmn3:0 bits are set to the fast p w m mode. n ote: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1/comnc1 is set. in this case t he compare match is ignored, but the set or clear is done at bottom. see ?fast p w m mode? on page 150. for more details. table 17-3. compare output mode, non-p w m comna1 comnb1 comnc1 comna0 comnb0 comnc0 description 00 n ormal port operation, ocna/ocnb/ocnc disconnected 0 1 toggle ocna/ocnb/ocnc on compare match 1 0 clear ocna/ocnb/ocnc on compare match (set output to low level) 1 1 set ocna/ocnb/ocnc on compare match (set output to high level) table 17-4. compare output mode, fast p w m comna1 comnb1 comnc1 comna0 comnb0 comnc0 description 00 n ormal port operation, ocna/ocnb/ocnc disconnected 01 w gm13:0 = 14 or 15: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other w gm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected 10 clear ocna/ocnb/ocnc on compare match, set ocna/ocnb/ocnc at bottom (non-inverting mode) 11 set ocna/ocnb/ocnc on compare match, clear ocna/ocnb/ocnc at bottom (inverting mode)
160 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 17-5 shows the comnx1:0 bit functionality when the w gmn3:0 bits are set to the phase correct and frequency correct p w m mode. n ote: a special case occurs when ocrna/ocrnb/ocrnc equals top and comna1/comnb1//comnc1 is set. see ?phase correct p w m mode? on page 152. for more details. 17.11.5 tccr1b ? timer/counter 1 control register b 17.11.6 tccr3b ? timer/counter 3 control register b 17.11.7 tccr4b ? timer/counter 4 control register b 17.11.8 tccr5b ? timer/counter 5 control register b ? bit 7 ? icncn: input capture noise canceler setting this bit (to one) activates the input capture n oise canceler. w hen the n oise canceler is activated, the input from the input capture pin (icpn) is filtered. the filter function requires four successive equal valued samples of the icpn pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. table 17-5. compare output mode, phase correct and phase and frequency correct p w m comna1 comnb1 comnc1 comna0 comnb0 comnc0 description 00 n ormal port operation, ocna/ocnb/ocnc disconnected 01 w gm13:0 =9 or 11: toggle oc1a on compare match, oc1b and oc1c disconnected (normal port operation). for all other w gm1 settings, normal port operation, oc1a/oc1b/oc1c disconnected 10 clear ocna/ocnb/ocnc on compare match when up-counting set ocna/ocnb/ocnc on compare match when downcounting 11 set ocna/ocnb/ocnc on compare match when up-counting clear ocna/ocnb/ocnc on compare match when downcounting bit 76543210 (0x81) icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/ w rite r/ w r/ w rr/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 7 6 5 4 3 2 1 0 (0x91) icnc3 ices3 ? wgm33 wgm32 cs32 cs31 cs30 tccr3b read/ w rite r/ w r/ w rr/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xa1) icnc4 ices4 ? wgm43 wgm42 cs42 cs41 cs40 tccr4b read/ w rite r/ w r/ w rr/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x121) icnc5 ices5 ? wgm53 wgm52 cs52 cs51 cs50 tccr5b read/ w rite r/ w r/ w rr/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
161 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 ? icesn: input capture edge select this bit selects which edge on the input capture pin (icpn) that is used to trigger a capture event. w hen the icesn bit is written to zero, a fa lling (negative) edge is used as trigger, and when the icesn bit is written to one, a risi ng (positive) edge w ill trigger the capture. w hen a capture is triggered according to the icesn setting, the counter value is copied into the input capture register (icrn). the event will also set the input capture flag (icfn), and this can be used to cause an input capture interrupt, if this interrupt is enabled. w hen the icrn is used as top value (see description of the w gmn3:0 bits located in the tccrna and the tccrnb register), the icpn is disconnected and consequently the input cap- ture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future de vices, this bit must be written to zero when tccrnb is written. ? bit 4:3 ? wgmn3:2: waveform generation mode see tccrna register description. ? bit 2:0 ? csn2:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 17-10 on page 156 and figure 17-11 on page 156 . if external pin modes are used for the timer/countern, transitions on the tn pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 17.11.9 tccr1c ? timer/counter 1 control register c table 17-6. clock select bit description csn2 csn1 csn0 description 000 n o clock source. (timer/counter stopped) 001 clk i/o /1 ( n o prescaling 010 clk i/o /8 (from prescaler) 011 clk i/o /64 (from prescaler) 100 clk i/o /256 (from prescaler) 101 clk i/o /1024 (from prescaler) 1 1 0 external clock source on tn pin. clock on falling edge 1 1 1 external clock source on tn pin. clock on rising edge bit 7654 3210 (0x82) foc1a foc1b foc1c ? ? ? ? ? tccr1c read/ w rite www r rrrr initial value 0 0 0 0 0 0 0 0
162 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.11.10 tccr3c ? timer/counter 3 control register c 17.11.11 tccr4c ? timer/counter 4 control register c 17.11.12 tccr5c ? timer/counter 5 control register c ? bit 7 ? focna: force output compare for channel a ? bit 6 ? focnb: force output compare for channel b ? bit 5 ? focnc: force output compare for channel c the focna/focnb/focnc bits are only active when the w gmn3:0 bits specifies a non-p w m mode. w hen writing a logical one to the focna/focnb/focnc bit, an immediate compare match is forced on the waveform generation unit. the ocna/ocnb/ocnc output is changed according to its comnx1:0 bits setting. n ote that the focna/focnb/focnc bits are imple- mented as strobes. therefore it is the value present in the comnx1:0 bits that determine the effect of the forced compare. a focna/focnb/focnc strobe will no t generate any interrupt nor w ill it clear the timer in clear timer on compare match (ctc) mode using ocrna as top. the focna/focnb/focnb bits are always read as zero. ? bit 4:0 ? reserved bits these bits are reserved for future use. for ensuring compatibility with future devices, these bits must be written to zero when tccrnc is written. 17.11.13 tcnt1h and tcnt1l ? timer/counter 1 17.11.14 tcnt3h and tcnt3l ? timer/counter 3 bit 7654 3210 (0x92) foc3a foc3b foc3c ? ? ? ? ? tccr3c read/ w rite www r rrrr initial value 0 0 0 0 0 0 0 0 bit 7654 3210 (0xa2) foc4a foc4b foc4c ? ? ? ? ? tccr4c read/ w rite www r rrrr initial value 0 0 0 0 0 0 0 0 bit 7654 3210 (0x122) foc5a foc5b foc3c ? ? ? ? ? tccr5c read/ w rite www r rrrr initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x85) tcnt1[15:8] tcnt1h (0x84) tcnt1[7:0] tcnt1l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x95) tcnt3[15:8] tcnt3h (0x94) tcnt3[7:0] tcnt3l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
163 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.11.15 tcnt4h and tcnt4l ?timer/counter 4 17.11.16 tcnt5h and tcnt5l ?timer/counter 5 the two timer/counter i/o locations (tc n tnh and tc n tnl, combined tc n tn) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is perfo rmed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 138. modifying the counter (tc n tn) while the counter is running introduces a risk of missing a com- pare match between tc n tn and one of the ocrnx registers. w riting to the tc n tn register blocks (removes) the compare match on the following timer clock for all compare units. 17.11.17 ocr1ah and ocr1al ? ou tput compare register 1 a 17.11.18 ocr1bh and ocr1bl ? ou tput compare register 1 b 17.11.19 ocr1ch and ocr1cl ? ou tput compare register 1 c bit 76543210 (0xa5) tcnt4[15:8] tcnt4h (0xa4) tcnt4[7:0] tcnt4l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x125) tcnt5[15:8] tcnt5h (0x124) tcnt5[7:0] tcnt5l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x89) ocr1a[15:8] ocr1ah (0x88) ocr1a[7:0] ocr1al read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x8b) ocr1b[15:8] ocr1bh (0x8a) ocr1b[7:0] ocr1bl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x8d) ocr1c[15:8] ocr1ch (0x8c) ocr1c[7:0] ocr1cl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
164 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.11.20 ocr3ah and ocr3al ? ou tput compare register 3 a 17.11.21 ocr3bh and ocr3bl ? ou tput compare register 3 b 17.11.22 ocr3ch and ocr3cl ? ou tput compare register 3 c 17.11.23 ocr4ah and ocr4al ? ou tput compare register 4 a 17.11.24 ocr4bh and ocr4bl ? ou tput compare register 4 b 17.11.25 ocr4ch and ocr4cl ?output compare register 4 c 17.11.26 ocr5ah and ocr5al ? ou tput compare register 5 a bit 76543210 (0x99) ocr3a[15:8] ocr3ah (0x98) ocr3a[7:0] ocr3al read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x9b) ocr3b[15:8] ocr3bh (0x9a) ocr3b[7:0] ocr3bl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x9d) ocr3c[15:8] ocr3ch (0x9c) ocr3c[7:0] ocr3cl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xa9) ocr4a[15:8] ocr4ah (0xa8) ocr4a[7:0] ocr4al read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xaa) ocr4b[15:8] ocr4bh (0xab) ocr4b[7:0] ocr4bl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xad) ocr4c[15:8] ocr4ch (0xac) ocr4c[7:0] ocr4cl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x129) ocr5a[15:8] ocr5ah (0x128) ocr5a[7:0] ocr5al read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
165 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 17.11.27 ocr5bh and ocr5bl ? ou tput compare register 5 b 17.11.28 ocr5ch and ocr5cl ?output compare register 5 c the output compare registers contain a 16-bit value that is continuously compared with the counter value (tc n tn). a match can be used to generate an output compare interrupt, or to generate a waveform output on the ocnx pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cp u writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 138. 17.11.29 icr1h and icr1l ? input capture register 1 17.11.30 icr3h and icr3l ? input capture register 3 17.11.31 icr4h and icr4l ? input capture register 4 17.11.32 icr5h and icr5l ? input capture register 5 bit 76543210 (0x12b) ocr5b[15:8] ocr5bh (0x12a) ocr5b[7:0] ocr5bl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x12d) ocr5c[15:8] ocr5ch (0x12c) ocr5c[7:0] ocr5cl read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x87) icr1[15:8] icr1h (0x86) icr1[7:0] icr1l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x97) icr3[15:8] icr3h (0x96) icr3[7:0] icr3l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xa7) icr4[15:8] icr4h (0xa6) icr4[7:0] icr4l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x127) icr5[15:8] icr5h (0x126) icr5[7:0] icr5l read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
166 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the input capture is updated with the counter (tc n tn) value each time an event occurs on the icpn pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these regi sters, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 138. 17.11.33 timsk1 ? ti mer/counter 1 interrupt mask register 17.11.34 timsk3 ? ti mer/counter 3 interrupt mask register 17.11.35 timsk4 ? ti mer/counter 4 interrupt mask register 17.11.36 timsk5 ? ti mer/counter 5 interrupt mask register ? bit 5 ? icien: timer/countern, input capture interrupt enable w hen this bit is written to one, and the i-flag in t he status register is set (interrupts globally enabled), the timer/countern input capture interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 105 ) is executed when the icfn flag, located in tifrn, is set. ? bit 3 ? ocienc: timer/countern, output compare c match interrupt enable w hen this bit is written to one, and the i-flag in t he status register is set (interrupts globally enabled), the timer/countern output compare c match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 105 ) is executed when the ocfnc flag, located in tifrn, is set. ? bit 2 ? ocienb: timer/countern, output compare b match interrupt enable w hen this bit is written to one, and the i-flag in t he status register is set (interrupts globally enabled), the timer/countern output compare b match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 105 ) is executed when the ocfnb flag, located in tifrn, is set. bit 76543210 (0x6f) ? ?icie1 ? ocie1c ocie1b ocie1a toie1 timsk1 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x71) ? ?icie3 ? ocie3c ocie3b ocie3a toie3 timsk3 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x72) ? ?icie4 ? ocie4c ocie4b ocie4a toie4 timsk4 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x73) ? ?icie5 ? ocie5c ocie5b ocie5a toie5 timsk5 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value00000000
167 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 1 ? ociena: timer/countern, output compare a match interrupt enable w hen this bit is written to one, and the i-flag in t he status register is set (interrupts globally enabled), the timer/countern output compare a match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 105 ) is executed when the ocfna flag, located in tifrn, is set. ? bit 0 ? toien: timer/countern, overflow interrupt enable w hen this bit is written to one, and the i-flag in t he status register is set (interrupts globally enabled), the timer/countern overflow interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 105 ) is executed when the tovn flag, located in tifrn, is set. 17.11.37 tifr1 ? timer/counte r1 interrupt flag register 17.11.38 tifr3 ? timer/counte r3 interrupt flag register 17.11.39 tifr4 ? timer/counte r4 interrupt flag register 17.11.40 tifr5 ? timer/counte r5 interrupt flag register ? bit 5 ? icfn: timer/count ern, input capture flag this flag is set when a capture event occurs on the icpn pin. w hen the input capture register (icrn) is set by the w gmn3:0 to be used as the top value, the icfn flag is set when the coun- ter reaches the top value. icfn is automatically cleared when the input capt ure interrupt vector is executed. alternatively, icfn can be cleared by writing a logic one to its bit location. ? bit 3? ocfnc: timer/countern, output compare c match flag this flag is set in the timer clock cycle after the counter (tc n tn) value matches the output compare register c (ocrnc). n ote that a forced output compare (foc nc) strobe will not set the ocfnc flag. ocfnc is automatically cleared when the output compare match c interrupt vector is exe- cuted. alternatively, ocfnc can be cleared by writing a logic one to its bit location. bit 76543210 0x16 (0x36) ? ?icf1 ? ocf1c ocf1b ocf1a tov1 tifr1 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x18 (0x38) ? ?icf3 ? ocf3c ocf3b ocf3a tov3 tifr3 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x19 (0x39) ? ?icf4 ? ocf4c ocf4b ocf4a tov4 tifr4 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1a (0x3a) ? ?icf5 ? ocf5c ocf5b ocf5a tov5 tifr5 read/ w rite r r r/ w rr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
168 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 2 ? ocfnb: timer/counter1, output compare b match flag this flag is set in the timer clock cycle after the counter (tc n tn) value matches the output compare register b (ocrnb). n ote that a forced output compare (focnb ) strobe will not set the ocfnb flag. ocfnb is automatically cleared when the output compare match b interrupt vector is exe- cuted. alternatively, ocfnb can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle after the counter (tc n tn value matches the output com- pare register a (ocrna). n ote that a forced output compare (focna ) strobe will not set the ocfna flag. ocfna is automatically cleared when the output compare match a interrupt vector is exe- cuted. alternatively, ocfna can be cleared by writing a logic one to its bit location. ? bit 0 ? tovn: timer/countern, overflow flag the setting of this flag is dependent of the w gmn3:0 bits setting. in n ormal and ctc modes, the tovn flag is set when the timer overflows. refer to table 17-2 on page 148 for the tovn flag behavior when using another w gmn3:0 bit setting. tovn is automatically cleared when the timer/c ountern overflow interrupt vector is executed. alternatively, tovn can be cleared by writing a logic one to its bit location.
169 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 18. timer/counter 0, 1, 3, 4, and 5 prescaler timer/counter 0, 1, 3, 4, and 5 share the same prescaler module, but the timer/counters can have different prescaler settings. the description below applies to all timer/counters. tn is used as a general name, n = 0, 1, 3, 4, or 5. 18.1 internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn2:0 = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. 18.2 prescaler reset the prescaler is free running, that is, operates independently of the clock select logic of the timer/counter, and it is shared by the timer/counter tn. since the prescaler is not affected by the timer/counter?s clock select, the state of the prescaler will ha ve implications for situations where a prescaled clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n +1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing the timer/counter to program execu- tion. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a prescaler reset will affect the prescaler period for all timer/coun ters it is connected to. 18.3 external clock source an external clock source applied to the tn pin can be used as timer/counter clock (clk tn ). the tn pin is sampled once every system clock cycle by the pin synchronization logic. the synchro- nized (sampled) signal is then passed through the edge detector. figure 18-1 shows a functional equivalent block diagram of the tn synchronizati on and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk tn pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 18-1. tn/t0 pin sampling tn_sync (to clock s elect logic) edge detector s ynchronization dq dq le dq tn clk i/o
170 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the synchronization and e dge detector logic introduces a de lay of 2.5 to 3.5 system clock cycles from an edge has been applied to the tn pin to the counter is updated. enabling and disabling of the clock input must be done when tn has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the external clock applie d must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the sys- tem clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling fre- quency ( n yquist sampling theorem). however, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 18-2. prescaler for synchronous timer/counters 18.4 register description 18.4.1 gtccr ? general timer/counter control register ? bit 7 ? tsm: timer/counter synchronization mode w riting the tsm bit to one activates the timer/counter synchronization mode. in this mode, the value that is written to the psrasy and psrsy n c bits is kept, hence keeping the correspond- ing prescaler reset signals asserted. this ensures that the corresponding timer/counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. w hen the tsm bit is written to zero, the psrasy and psrsy n c bits are cleared by hardware, and the timer/counte rs start counting simultaneously. p s r10 clear tn tn clk i/o s ynchronization s ynchronization timer/countern clock s ource clk tn timer/countern clock s ource clk tn c s n0 c s n1 c s n2 c s n0 c s n1 c s n2 bit 7 6 5 4 3 2 1 0 0x23 (0x43) tsm ? ? ? ? ? psrasy psrsync gtccr read/ w rite r/ w rrrrrr/ w r/ w initial value 0 0 0 0 0 0 0 0
171 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? psrsync: prescaler reset for synchronous timer/counters w hen this bit is one, timer/counter0, timer/c ounter1, timer/counter3, timer/counter4 and timer/counter5 prescaler will be re set. this bit is normally cl eared immediatel y by hardware, except if the tsm bit is set. n ote that timer/counter0, timer/counter1, timer/counter3, timer/counter4 and timer/counte r5 share the same prescaler and a reset of this prescaler will affect all timers.
172 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 19. output compare modulator (ocm1c0a) 19.1 overview the output compare modulator (ocm) allows generation of waveforms modulated with a carrier frequency. the modulator uses the outputs from the output compare unit c of the 16-bit timer/counter1 and the output compare unit of the 8-bit timer/counter0. for more details about these timer/counters see ?timer/counter 0, 1, 3, 4, and 5 prescaler? on page 169 and ?8- bit timer/counter2 with p w m and asynchronous operation? on page 174 . figure 19-1. output compare modulator, block diagram w hen the modulator is enabled, the two output compare channels are modulated together as shown in the block diagram (see figure 19-1 ). 19.2 description the output compare unit 1c and output compare unit 2 shares the pb7 port pin for output. the outputs of the output compare units (oc1c and oc0a) overrides the normal portb7 register when one of them is enabled (that is, when comnx1:0 is not equal to zero). w hen both oc1c and oc0a are enabled at the same time, the modulator is automatically enabled. the functional equivalent schematic of the modulator is shown on figure 19-2 . the schematic includes part of the timer/counter units and the port b pin 7 output driver circuit. figure 19-2. output compare modulator, schematic oc1c pin oc1c / oc0a / pb7 timer/counter 1 timer/counter 0 oc0a portb7 ddrb7 dq dq pin coma01 coma00 databus oc1c / oc0a/ pb7 com1c1 com1c0 modulator 1 0 oc1c dq oc0a dq ( from waveform generator ) ( from waveform generator ) 0 1 vcc
173 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w hen the modulator is enabled the type of modulation (logical a n d or or) can be selected by the portb7 register. n ote that the ddrb7 controls the direction of the port independent of the comnx1:0 bit setting. 19.2.1 timing example figure 19-3 illustrates the modulator in ac tion. in this example the ti mer/counter1 is set to oper- ate in fast p w m mode (non-inverted) and timer/counter0 uses ctc waveform mode with toggle compare output mode (comnx1:0 = 1). figure 19-3. output compare modulator, timing diagram in this example, timer/counter2 provides the carrier, while the modulating signal is generated by the output compare unit c of the timer/counter1. the resolution of the p w m signal (oc1c) is reduced by the modulation. the reduction factor is equal to the number of system clock cycles of one period of the carrier (oc0a). in this example the resolution is reduced by a factor of two. the reason for the reduction is illustrated in figure 19-3 at the second and third period of the pb7 output when portb7 equals zero. the period 2 high time is one cycle longer than the period 3 high time, but the result on the pb7 output is equal in both periods. 1 2 oc0a (ctc mode) oc1c (fpwm mode) pb7 (portb7 = 0) pb7 (portb7 = 1) (period) 3 clk i/o
174 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20. 8-bit timer/counter2 with pwm and asynchronous operation timer/counter2 is a general purpose, single channel, 8-bit timer/counter module. the main features are: ? single channel counter ? clear timer on compare match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? frequency generator ? 10-bit clock prescaler ? overflow and compare ma tch interrupt sources (tov2, ocf2a and ocf2b) ? allows clocking from external 32khz watch crystal independent of the i/o clock 20.1 overview a simplified block diagram of the 8-bit timer/counter is shown in figure 17-12. for the actual placement of i/o pins, see ?pin configurations? on page 2 . cpu accessible i/o registers, includ- ing i/o bits and i/o pins, are shown in bold. t he device-specific i/o register and bit locations are listed in the ?register description? on page 187 . the power reduction timer/counter2 bit, prtim2, in ?prr0 ? power reduction register 0? on page 56 must be written to zero to enable timer/counter2 module. figure 20-1. 8-bit timer/counter block diagram timer/counter data bus ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb clk tn assrn synchronization unit prescaler t/c oscillator clk i/o clk asy asynchronous mode select (asn) synchronized status flags tosc1 tosc2 status flags clk i/o
175 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.1.1 registers the timer/counter (tc n t2) and output compare register (ocr2a and ocr2b) are 8-bit reg- isters. interrupt request (abbreviated to int.req.) signals are all visible in the timer interrupt flag register (tifr2). all interrupts are individua lly masked with the timer interrupt mask register (timsk2). tifr2 and timsk2 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or asynchronously clocked from the tosc1/2 pins, as detailed later in this section. the asynchronous operation is controlled by the asynchronous status regist er (assr). the clock select lo gic block controls which clock source the timer/counter uses to increment (or de crement) its value. the timer/counter is inac- tive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t2 ). the double buffered output compare register (ocr2a and ocr2b) are compared with the timer/counter value at all times. the result of the compare can be used by the w aveform gen- erator to generate a p w m or variable frequency output on the output compare pins (oc2a and oc2b). see ?output compare unit? on page 180 for details. the comp are match event will also set the compare flag (ocf2a or ocf2b) which can be used to generate an output compare interrupt request. 20.1.2 definitions many register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, in this case 2. however, when using the register or bit defines in a program, the precise form must be used, that is, tc n t2 for accessing timer/counter2 counter value and so on. the definitions in table 20-1 are also used extensively throughout the section. 20.2 timer/counter clock sources the timer/counter can be clocked by an internal synchronous or an external asynchronous clock source. the clock source clk t2 is by default equal to the mcu clock, clk i/o . w hen the as2 bit in the assr register is written to logic one, the clock source is taken from the timer/counter oscillator connecte d to tosc1 and tosc2. for details on asynchronous operation, see ?asyn- chronous operation of timer/counter2? on page 184 . for details on clock sources and prescaler, see ?timer/counter prescaler? on page 186 . 20.3 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 20-2 on page 176 shows a block diagram of the counter and its surrounding environment. table 20-1. definitions bottom the counter reaches the bottom when it becomes zero (0x00) max the counter reaches its maximum when it becomes 0xff (decimal 255) top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr2a register. the assignment is dependent on the mode of operation
176 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 20-2. counter unit block diagram signal description (internal signals): count increment or decrement tc n t2 by 1. direction selects between increment and decrement. clear clear tc n t2 (set all bits to zero). clk tn timer/counter clock, referred to as clk t2 in the following. top signalizes that tc n t2 has reached maximum value. bottom signalizes that tc n t2 has reached minimum value (zero). depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t2 ). clk t2 can be generated from an external or internal clock source, selected by the clock select bits (cs22:0). w hen no clock source is selected (cs22:0 = 0) the timer is stopped. however, the tc n t2 value can be accessed by the cpu, regardless of whether clk t2 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the w gm21 and w gm20 bits located in the timer/counter control register (tccr2a) and the w gm22 located in the timer/counter control register b (tccr2b). there are clos e connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc2a and oc2b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 176 . the timer/counter overflow flag (tov2) is set according to the mode of operation selected by the w gm22:0 bits. tov2 can be used for generating a cpu interrupt. 20.4 modes of operation the mode of operation, that is, the behavior of the timer/counter and the output compare pins, is defined by the combination of the w aveform generation mode ( w gm22:0) and compare out- put mode (com2x1:0) bits. the compare output mode bits do not affect the counting sequence, while the w aveform generation mode bits do. the com2x1:0 bits control whether the p w m out- put generated should be inverted or not (inverted or non-inverted p w m). for non-p w m modes the com2x1:0 bits control whether the output should be set, cleared, or toggled at a compare match. see ?compare match output unit? on page 182. for detailed timing information refer to ?timer/counter timing diagrams? on page 183 . data b u s tcntn control logic count tovn (int.req.) top bottom direction clear tosc1 t/c oscillator tosc2 prescaler clk i/o clk tn
177 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.4.1 normal mode the simplest mode of operation is the n ormal mode ( w gm22:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal o peration the timer/counter overflow flag (tov2) will be set in the same timer clock cycle as the tc n t2 becomes zero. the tov2 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov2 flag, the timer resolution can be increased by software. there are no special cases to consider in the n ormal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in n ormal mode is not recommended, since this will occupy too much of the cpu time. 20.4.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode ( w gm22:0 = 2), the ocr2a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tc n t2) matches the ocr2a. the ocr2a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 20-3 . the counter value (tc n t2) increases until a compare match occurs between tc n t2 and ocr2a, and then counter (tc n t2) is cleared. figure 20-3. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf2a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr2a is lower than the current value of tc n t2, the counter will miss the compare matc h. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc2a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com2a1:0 = 1). the oc2a value will not be visible on the port pin unless the data direction for tcntn ocnx (toggle) ocnx interrupt flag s et 1 4 period 2 3 (comnx1:0 = 1)
178 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the pin is set to output. the wavefo rm generated will have a maximum frequency of f oc2a = f clk_i/o /2 when ocr2a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). as for the n ormal mode of operation, the tov2 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 20.4.3 fast pwm mode figure 20-4. fast p w m mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches top. if the inter- rupt is enabled, the interrupt handler routine can be used for updating the compare value. in fast p w m mode, the compare unit allows generation of p w m waveforms on the oc2x pin. setting the com2x1:0 bits to tw o will produce a non-inverted p w m and an inverted p w m output can be generated by setting the com2x1:0 to three. top is defined as 0xff when w gm2:0 = 3, and ocr2a when w gm2:0 = 7 (see table 20-3 on page 187 ). the actual oc2x value will only be visible on the port pin if the data direction for the port pin is set as output. the p w m wave- form is generated by setting (or clearing) the oc2x register at the compare match between ocr2x and tc n t2, and clearing (or setting) the oc2x register at the ti mer clock cycle the counter is cleared (changes from top to bottom). the p w m frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr2a register represent special cases when generating a p w m waveform output in the fast p w m mode. if the ocr2a is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr2a equal to max will result f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------- - = tcntn ocrnx update and tovn interrupt flag s et 1 period 2 3 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag s et 4 5 6 7 f ocnxpwm f clk_i/o n 256 ? ------------------ =
179 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 in a constantly high or low output (depending on the polarity of the output set by the com2a1:0 bits). a frequency (with 50% duty cycle) waveform output in fast p w m mode can be achieved by set- ting oc2x to toggle its logical level on each compare match (com2x1:0 = 1). the waveform generated will have a ma ximum frequency of f oc2 = f clk_i/o /2 when ocr2a is set to zero. this fea- ture is similar to the oc2a toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast p w m mode. 20.4.4 phase correct pwm mode the phase correct p w m mode ( w gm22:0 = 1 or 5) provides a high resolution phase correct p w m waveform generation option. the phase correct p w m mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bot- tom. top is defined as 0xff when w gm22:0 = 1, and ocr2a when mgm22:0 = 5. in non- inverting compare output mode, the output compare (oc2x) is cleared on the compare match between tc n t2 and ocr2x while upcounting, and set on the compare match while downcount- ing. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmet- ric feature of the dual-slope p w m modes, these modes are preferred for motor control applications. in phase correct p w m mode the counter is incremented until the counter value matches top. w hen the counter reaches top, it changes the count direction. the tc n t2 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct p w m mode is shown on figure 20-5 . the tc n t2 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted p w m outputs. the small horizontal line marks on the tc n t2 slopes represent compare matches between ocr2x and tc n t2. figure 20-5. phase correct p w m mode, timing diagram tovn interrupt flag s et ocnx interrupt flag s et 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update
180 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the timer/counter overflow flag (tov2) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct p w m mode, the compare unit allows generation of p w m waveforms on the oc2x pin. setting the com2x1:0 bits to two will produce a non-inverted p w m. an inverted p w m output can be generated by setting the com2x1:0 to three. top is defined as 0xff when w gm2:0 = 3, and ocr2a when mgm2:0 = 7 (see table 20-4 on page 188 ). the actual oc2x value will only be visible on the port pin if the data direction for the port pin is set as output. the p w m waveform is generated by clearing (or setting) the oc2x register at the compare match between ocr2x and tc n t2 when the counter increments, and setting (or clearing) the oc2x register at compare match between ocr2x and tc n t2 when the counter decrements. the p w m frequency for the output when using phase correct p w m can be calculated by the follow- ing equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr2a register represent special cases when generating a p w m waveform output in the phase correct p w m mode. if the ocr2a is set equal to bottom, the output will be continuously low an d if set equal to max the output will be continuously high for non-inverted p w m mode. for inverted p w m the output will have th e opposite logic values. at the very start of period 2 in figure 20-5 on page 179 ocnx has a transition from high to low even though there is no compare match. the poin t of this transition is to guarantee symmetry around bottom. there are two cases that give a transition without compare match. ? ocr2a changes its value from max, like in figure 20-5 on page 179 . w hen the ocr2a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match. ? the timer starts counting from a value higher than the one in ocr2a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 20.5 output compare unit the 8-bit comparator continuously compares tc n t2 with the output compare register (ocr2a and ocr2b). w henever tc n t2 equals ocr2a or ocr2b, the comparator signals a match. a match will set the output compare flag (ocf2a or ocf2b) at the next timer clock cycle. if the corresponding interrupt is enabled, the output compare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is exe- cuted. alternatively, the output compare flag can be cleared by software by writing a logical one to its i/o bit location. the w aveform generator uses the match signal to generate an output according to operating mode set by the w gm22:0 bits and compare output mode (com2x1:0) bits. the max and bottom signals are used by the w aveform generator for handling the special cases of the extreme values in some modes of operation (see ?modes of operation? on page 176 ). figure 20-6 on page 181 shows a block diagram of the output compare unit. f ocnxpcpwm f clk_i/o n 510 ? ------------------ =
181 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 20-6. output compare unit, block diagram the ocr2x register is double buffered when using any of the pulse w idth modulation (p w m) modes. for the n ormal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr2x compare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical p w m pulses, thereby making the output glitch-free. the ocr2x register access may seem complex, but this is not case. w hen the double buffering is enabled, the cpu has access to the ocr2x buffer register, and if double buffering is dis- abled the cpu will access the ocr2x directly. 20.5.1 force output compare in non-p w m waveform generation modes, the match output of the comparator can be forced by writing a one to the force outp ut compare (foc2x) bit. forci ng compare match will not set the ocf2x flag or reload/clear the timer, but the oc2x pin will be updated as if a real compare match had occurred (the com2x1:0 bits settings de fine whether the oc2x pin is set, cleared or toggled). 20.5.2 compare match bloc king by tcnt2 write all cpu write operations to the tc n t2 register will block any compar e match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr2x to be initial- ized to the same value as tc n t2 without triggering an interrupt when the timer/counter clock is enabled. 20.5.3 using the output compare unit since writing tc n t2 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tc n t2 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tc n t2 equals the ocr2x value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write the tc n t2 value equal to bottom when the counter is downcounting. ocfn x (int.req.) = ( 8 -bit comparator ) ocrnx ocnx data b u s tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
182 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the setup of the oc2x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc2x value is to use the force output com- pare (foc2x) strobe bit in n ormal mode. the oc2x register keeps its value even when changing between w aveform generation modes. be aware that the com2x1:0 bits are not doubl e buffered together with the compare value. changing the com2x1:0 bits will take effect immediately. 20.6 compare match output unit the compare output mode (com2x1:0) bits have two functions. the w aveform generator uses the com2x1:0 bits for defining the output compare (oc2x) state at the next compare match. also, the com2x1:0 bits control the oc2x pin output source. figure 20-7 shows a simplified schematic of the logic affected by the com2x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com2x1:0 bits are shown. w hen referring to the oc2x state, the reference is for the internal oc2x register, not the oc2x pin. figure 20-7. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc2x) from the w aveform generator if either of the com2x1:0 bits are set. however, the oc2x pin direction (input or out- put) is still controlled by the da ta direction register (ddr) for th e port pin. the data direction register bit for the oc2x pin (ddr_oc2x) must be set as output before the oc2x value is visi- ble on the pin. the port override function is independent of the w aveform generation mode. the design of the output compare pin logic allows initialization of the oc2x state before the out- put is enabled. n ote that some com2x1:0 bit settings are reserved for certain modes of operation. see ?register description? on page 187. port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
183 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.6.1 compare output mode and waveform generation the w aveform generator uses the com2x1:0 bits differently in normal, ctc, and p w m modes. for all modes, setting the com2x1:0 = 0 tells the w aveform generator that no action on the oc2x register is to be performed on the next compare match. for compare output actions in the non-p w m modes refer to table 20-5 on page 188 . for fast p w m mode, refer to table 20-6 on page 188 , and for phase correct p w m refer to table 20-7 on page 189 . a change of the com2x1:0 bits st ate will have effect at the first compare match after the bits are written. for non-p w m modes, the action can be forced to have immediate effect by using the foc2x strobe bits. 20.7 timer/counter timing diagrams the following figures show the timer/counter in synchronous mode, and the timer clock (clk t2 ) is therefore shown as a clock enable signal. in asynchronous mode, clk i/o should be replaced by the timer/counter oscillator clock. the figures include information on when interrupt flags are set. figure 20-8 contains timing data for basic timer/ counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct p w m mode. figure 20-8. timer/counter timing diagram, no prescaling figure 20-9 shows the same timing data, but with the prescaler enabled. figure 20-9. timer/counter timing dia gram, with prescaler (f clk_i/o /8) clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1 tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o / 8 )
184 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 20-10 shows the setting of ocf2a in all modes except ctc mode. figure 20-10. timer/counter timing diagram, setting of ocf2a, with prescaler (f clk_i/o /8) figure 20-11 shows the setting of ocf2a and the clearing of tc n t2 in ctc mode. figure 20-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) 20.8 asynchronous operati on of timer/counter2 w hen timer/counter2 operates asynchronously, some considerations must be taken. ? w arning: w hen switching between asynchronous and synchronous clocking of timer/counter2, the timer registers tc n t2, ocr2x, and tccr2x might be corrupted. a safe procedure for switching clock source is: 1. disable the timer/counter2 interrupts by clearing ocie2x and toie2. 2. select clock source by setting as2 as appropriate. 3. w rite new values to tc n t2, ocr2x, and tccr2x. 4. to switch to asynchronous operation: w ait for tc n 2ub, ocr2xub, and tcr2xub. 5. clear the timer/counter2 interrupt flags. 6. enable interrupts, if needed. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o / 8 ) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o / 8 )
185 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? the cpu main clock frequenc y must be more than four times the oscillator frequency. ? w hen writing to one of the registers tc n t2, ocr2x, or tccr2x, the value is transferred to a temporary register, and latched after two positive edges on tosc1. the user should not write a new value before the contents of the temporary register have been transferred to its destination. each of the five mentioned registers have their individual temporary register, which means that, for example, writing to tc n t2 does not disturb an ocr2x write in progress. to detect that a transfer to the destination register has taken place, the asynchronous status register ? assr has been implemented. ? w hen entering power-save or adc n oise reduction mode after having written to tc n t2, ocr2x, or tccr2x, the user must wait until the written register has been updated if timer/counter2 is used to wake up the device. other wise, the mcu will enter sleep mode before the changes are effective. this is particularly important if any of the output compare2 interrupt is used to wake up the device, since the output compare function is disabled during writing to ocr2x or tc n t2. if the write cycle is not finished, and the mcu enters sleep mode befo re the corresponding ocr2xub bit returns to zero, the device will never receive a compare match interr upt, and the mcu will not wake up. ? if timer/counter2 is used to wake the device up from power-save or adc n oise reduction mode, precautions must be taken if the user wants to re-enter one of these modes: the interrupt logic needs one tosc1 cycle to be reset. if the time between wake-up and re- entering sleep mode is less than one tosc1 cycle, the interrupt will not occur, and the device will fail to wake up. if the user is in doubt whether the time be fore re-entering power- save or adc n oise reduction mode is sufficient, the following algorithm can be used to ensure that one tosc1 cycle has elapsed: 1. w rite a value to tccr2x, tc n t2, or ocr2x. 2. w ait until the corresponding update busy flag in assr returns to zero. 3. enter power-save or adc n oise reduction mode. ? w hen the asynchronous ope ration is selected, the 32.768kh z oscillator for timer/counter2 is always running, except in power-down and standby modes. after a power-up reset or wake-up from power-down or standby mode, the user should be aware of the fact that this oscillator might take as long as one second to stabilize. the us er is advised to wait for at least one second before using timer/counter2 after power-up or wake-up from power-down or standby mode. the contents of all timer/counter2 registers must be considered lost after a wake-up from power-down or standby mode due to unstable clock signal upon start- up, no matter whether the oscillator is in use or a clock signal is applied to the tosc1 pin. ? description of wake up from power-save or adc n oise reduction mode when the timer is clocked asynchronously: w hen the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. after wake-up, the mcu is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following sleep. ? reading of the tc n t2 register shortly after wake-up from power-save may give an incorrect result. since tc n t2 is clocked on the asynchronous tosc clock, reading tc n t2 must be done through a register synchronized to the internal i/o clock domain. synchronization takes place for every rising tosc1 edge. w hen waking up from power- save mode, and the i/o clock (clk i/o ) again becomes active, tc n t2 will read as the previous value (before entering sleep) until the next rising tosc1 edge. the phase of the tosc clock after waking up from power-save mode is essentially unpredictable, as it depends on the wake-up time. the recommended procedure for reading tc n t2 is thus as follows: 1. w rite any value to either of the registers ocr2x or tccr2x. 2. w ait for the corresponding update busy flag to be cleared. 3. read tc n t2.
186 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? during asynchronous operation, the synchronization of the interrupt flags for the asynchronous timer takes three p rocessor cycles plus one timer cycle. the timer is therefore advanced by at least one before the processo r can read the timer value causing the setting of the interrupt flag. the output compare pi n is changed on the timer clock and is not synchronized to the processor clock. 20.9 timer/counter prescaler figure 20-12. prescaler for timer/counter2 the clock source for timer/counter2 is named clk t2s . clk t2s is by default connected to the main system i/o clock clk i o . by setting the as2 bit in assr, timer/counter2 is asynchronously clocked from the tosc1 pin. this enables us e of timer/counter2 as a real time counter (rtc). w hen as2 is set, pins tosc1 and tosc2 are disconnected from port c. a crystal can then be connected between the tosc1 and tosc2 pins to serve as an independent clock source for timer/counter2. the oscillator is optimized for use with a 32.768khz crystal. by set- ting the exclk bit in the assr, a 32khz external clock can be applied. see ?assr ? asynchronous status register? on page 192 for details. for timer/counter2, the possible prescaled selections are: clk t2s /8, clk t2s /32, clk t2s /64, clk t2s /128, clk t2s /256, and clk t2s /1024. additionally, clk t2s as well as 0 (stop) may be selected. setting the psrasy bit in gtccr resets the prescale r. this allows the user to operate with a predictable prescaler. 10-bit t/c pre s caler timer/counter2 clock s ource clk i/o clk t2 s to s c1 a s 2 c s 20 c s 21 c s 22 clk t2 s / 8 clk t2 s /64 clk t2 s /12 8 clk t2 s /1024 clk t2 s /256 clk t2 s /32 0 p s ra s y clear clk t2
187 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.10 register description 20.10.1 tccr2a ?timer/counter control register a ? bits 7:6 ? com2a1:0: compare match output a mode these bits control the output compare pin (oc2a) behavior. if one or both of the com2a1:0 bits are set, the oc2a output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction re gister (ddr) bit corresponding to the oc2a pin must be set in order to enable the output driver. w hen oc2a is connected to the pin, the function of the com2a1:0 bits depends on the w gm22:0 bit setting. table 20-2 shows the com2a1:0 bit functionality when the w gm22:0 bits are set to a normal or ctc mode (non-p w m). table 20-3 shows the com2a1:0 bit functionality when the w gm21:0 bits are set to fast p w m mode. n ote: 1. a special case occurs when ocr2a equals to p and com2a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at bottom. see ?fast p w m mode? on page 178 for more details. table 20-4 on page 188 shows the com2a1:0 bi t functionality when the w gm22:0 bits are set to phase correct p w m mode. bit 7 6 5 4 3 2 1 0 (0xb0) com2a1 com2a0 com2b1 com2b0 ? ? wgm21 wgm20 tccr2a read/ w rite r/ w r/ w r/ w r/ w rrr/ w r/ w initial value 0 0 0 0 0 0 0 0 table 20-2. compare output mode, non-p w m mode com2a1 com2a0 description 00 n ormal port operation, oc2a disconnected 0 1 toggle oc2a on compare match 1 0 clear oc2a on compare match 1 1 set oc2a on compare match table 20-3. compare output mode, fast p w m mode (1) com2a1 com2a0 description 00 n ormal port operation, oc2a disconnected 01 w gm22 = 0: n ormal port operation, oc2a disconnected w gm22 = 1: toggle oc2a on compare match 10 clear oc2a on compare match, set oc2a at bottom (non-inverting mode) 11 set oc2a on compare match, clear oc2a at bottom (inverting mode)
188 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. a special case occurs when ocr2a equals to p and com2a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct p w m mode? on page 179 for more details. ? bits 5:4 ? com2b1:0: compare match output b mode these bits control the output compare pin (oc2b) behavior. if one or both of the com2b1:0 bits are set, the oc2b output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction re gister (ddr) bit corresponding to the oc2b pin must be set in order to enable the output driver. w hen oc2b is connected to the pin, the function of the com2b1:0 bits depends on the w gm22:0 bit setting. table 20-5 shows the com2b1:0 bit functionality when the w gm22:0 bits are set to a normal or ctc mode (non-p w m). table 20-6 shows the com2b1:0 bit functionality when the w gm22:0 bits are set to fast p w m mode. n ote: 1. a special case occurs when ocr2b equals to p and com2b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at bottom. see ?fast p w m mode? on page 178 for more details. table 20-4. compare output mode, phase correct p w m mode (1) com2a1 com2a0 description 00 n ormal port operation, oc2a disconnected 01 w gm22 = 0: n ormal port operation, oc2a disconnected w gm22 = 1: toggle oc2a on compare match 10 clear oc2a on compare match when up-counting set oc2a on compare match when down-counting 11 set oc2a on compare match when up-counting clear oc2a on compare match when down-counting table 20-5. compare output mode, non-p w m mode com2b1 com2b0 description 00 n ormal port operation, oc2b disconnected 0 1 toggle oc2b on compare match 1 0 clear oc2b on compare match 1 1 set oc2b on compare match table 20-6. compare output mode, fast p w m mode (1) com2b1 com2b0 description 00 n ormal port operation, oc2b disconnected 01 reserved 10 clear oc2b on compare match, set oc2b at bottom (non-inverting mode) 11 set oc2b on compare match, clear oc2b at bottom (inverting mode)
189 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 20-7 shows the com2b1:0 bit functionality when the w gm22:0 bits are set to phase cor- rect p w m mode. n ote: 1. a special case occurs when ocr2b equals to p and com2b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct p w m mode? on page 179 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bits 1:0 ? wgm21:0: waveform generation mode combined with the w gm22 bit found in the tccr2b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of wave- form generation to be used, see table 20-8 . modes of operation supported by the timer/counter unit are: n ormal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse w idth modulation (p w m) modes (see ?modes of operation? on page 176 ). n otes: 1. max = 0xff. 2. bottom = 0x00. table 20-7. compare output mode, phase correct p w m mode (1) com2b1 com2b0 description 00 n ormal port operation, oc2b disconnected 01 reserved 10 clear oc2b on compare match when up-counting set oc2b on compare match when down-counting 11 set oc2b on compare match when up-counting clear oc2b on compare match when down-counting table 20-8. w aveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0000 n ormal 0xff immediate max 1001 p w m, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3011 fast p w m0xffbottommax 4100 reserved ? ? ? 5101 p w m, phase correct ocra top bottom 6110 reserved ? ? ? 7111 fast p w m ocra bottom top
190 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.10.2 tccr2b ? timer/counter control register b ? bit 7 ? foc2a: force output compare a the foc2a bit is only active when the w gm bits specify a non-p w m mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr2b is written when operating in p w m mode. w hen writing a logical one to the foc2a bit, an immediate compare match is forced on the w aveform generation unit. the oc2a output is changed according to its com2a1:0 bits setting. n ote that the foc2a bit is implemented as a strobe. therefore it is the value present in the com2a1:0 bits that determines the effect of the forced compare. a foc2a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr2a as top. the foc2a bit is always read as zero. ? bit 6 ? foc2b: force output compare b the foc2b bit is only active when the w gm bits specify a non-p w m mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr2b is written when operating in p w m mode. w hen writing a logical one to the foc2b bit, an immediate compare match is forced on the w aveform generation unit. the oc2b output is changed according to its com2b1:0 bits setting. n ote that the foc2b bit is implemented as a strobe. therefore it is the value present in the com2b1:0 bits that determines the effect of the forced compare. a foc2b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr2b as top. the foc2b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 3 ? wgm22: waveform generation mode see the description in the ?tccr2a ?timer/counter control register a? on page 187 . ? bit 2:0 ? cs22:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see table 20-9 on page 191 . bit 7 6 5 4 3 2 1 0 (0xb1) foc2a foc2b ? ? wgm22 cs22 cs21 cs20 tccr2b read/ w rite ww rrr/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
191 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. 20.10.3 tcnt2 ? timer/counter register the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. w riting to the tc n t2 register blocks (removes) the compare match on the following timer clock. modifying the counter (tc n t2) while the counter is running, introduces a risk of missing a compare match between tc n t2 and the ocr2x registers. 20.10.4 ocr2a ? output compare register a the output compare register a contains an 8-bi t value that is continuously compared with the counter value (tc n t2). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc2a pin. 20.10.5 ocr2b ? output compare register b the output compare register b contains an 8-bi t value that is continuously compared with the counter value (tc n t2). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc2b pin. table 20-9. clock select bit description cs22 cs21 cs20 description 000 n o clock source (timer/counter stopped) 001 clk t2s /( n o prescaling) 010 clk t2s /8 (from prescaler) 011 clk t2s /32 (from prescaler) 100 clk t2s /64 (from prescaler) 101 clk t2s /128 (from prescaler) 110 clk t 2 s /256 (from prescaler) 111 clk t 2 s /1024 (from prescaler) bit 76543210 (0xb2) tcnt2[7:0] tcnt2 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xb3) ocr2a[7:0] ocr2a read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xb4) ocr2b[7:0] ocr2b read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
192 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 20.10.6 assr ? asynchronous status register ? bit 6 ? exclk: enable external clock input w hen exclk is written to one, and asynchronous clock is selected, the external clock input buf- fer is enabled and an external cl ock can be input on timer oscilla tor 1 (tosc1) pin instead of a 32khz crystal. w riting to exclk should be done before asynchronous operation is selected. n ote that the crystal oscillator will only run when this bit is zero. ? bit 5 ? as2: asynchronous timer/counter2 w hen as2 is written to zero, timer/counter2 is clocked from the i/o clock, clk i/o . w hen as2 is written to one, timer/counter2 is clocked from a crystal oscilla tor connected to the timer oscil- lator 1 (tosc1) pin. w hen the value of as2 is changed, the contents of tc n t2, ocr2a, ocr2b, tccr2a and tccr2b might be corrupted. ? bit 4 ? tcn2ub: timer/counter2 update busy w hen timer/counter2 operates asynchronously and tc n t2 is written, this bit becomes set. w hen tc n t2 has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that tc n t2 is ready to be updated with a new value. ? bit 3 ? ocr2aub: output co mpare register2 update busy w hen timer/counter2 operates asynchronously and ocr2a is written, this bit becomes set. w hen ocr2a has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that ocr2a is ready to be updated with a new value. ? bit 2 ? ocr2bub: output compare register2 update busy w hen timer/counter2 operates asynchronously and ocr2b is written, this bit becomes set. w hen ocr2b has been updated from the temporary storage register, this bit is cleared by hard- ware. a logical zero in this bit indicates that ocr2b is ready to be updated with a new value. ? bit 1 ? tcr2aub: timer/counter control register2 update busy w hen timer/counter2 operates asynchronously and tccr2a is written, this bit becomes set. w hen tccr2a has been updated from the temporary storage regi ster, this bit is cleared by hardware. a logical zero in this bit indicates that tccr2a is ready to be updated with a new value. ? bit 0 ? tcr2bub: timer/counter control register2 update busy w hen timer/counter2 operates asynchronously and tccr2b is written, this bit becomes set. w hen tccr2b has been updated from the temporary storage regi ster, this bit is cleared by hardware. a logical zero in this bit indicates that tccr2b is ready to be updated with a new value. if a write is performed to any of the five timer/counter2 registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. bit 7 6 5 4 3 2 1 0 (0xb6) ? exclk as2 tcn2ub ocr2aub ocr2bub tcr2aub tcr2bub assr read/ w rite r r/ w r/ w rr r r r initial value 0 0 0 0 0 0 0 0
193 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the mechanisms for reading tc n t2, ocr2a, ocr2b, tccr2a and tccr2b are different. w hen reading tc n t2, the actual timer value is read. w hen reading ocr2a, ocr2b, tccr2a and tccr2b the value in the temporary storage register is read. 20.10.7 timsk2 ? timer/counter2 interrupt mask register ? bit 2 ? ocie2b: timer/counter2 output compare match b interrupt enable w hen the ocie2b bit is written to one and the i-bit in the status register is set (one), the timer/counter2 compare match b interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter2 occurs, that is, when the ocf2b bit is set in the timer/counter 2 interrupt flag register ? tifr2. ? bit 1 ? ocie2a: timer/counter2 output compare match a interrupt enable w hen the ocie2a bit is written to one and the i-bit in the status register is set (one), the timer/counter2 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter2 occurs, that is, when the ocf2a bit is set in the timer/counter 2 interrupt flag register ? tifr2. ? bit 0 ? toie2: timer/counter2 overflow interrupt enable w hen the toie2 bit is written to one and the i-bit in the status register is set (one), the timer/counter2 overflow interrupt is enabled. the corresponding interrupt is executed if an overflow in timer/counter2 occurs, that is, when the tov2 bit is set in the timer/counter2 inter- rupt flag register ? tifr2. 20.10.8 tifr2 ? timer/counter2 interrupt flag register ? bit 2 ? ocf2b: output compare flag 2 b the ocf2b bit is set (one) when a compare match occurs between the timer/counter2 and the data in ocr2b ? output compare register2. ocf2b is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, ocf2b is cleared by writing a logic one to the flag. w hen the i-bit in sreg, ocie2b (timer/counter2 compare match interrupt enable), and ocf2b are set (one), the timer/counter2 compare match interrupt is executed. ? bit 1 ? ocf2a: output compare flag 2 a the ocf2a bit is set (one) when a compare match occurs between the timer/counter2 and the data in ocr2a ? output compare register2. ocf2a is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, ocf2a is cleared by writing a logic one to the flag. w hen the i-bit in sreg, ocie2a (timer/counter2 compare match interrupt enable), and ocf2a are set (one), the timer/counter2 compare match interrupt is executed. bit 76543 2 1 0 (0x70) ? ? ? ? ? ocie2b ocie2a toie2 timsk2 read/ w rite rrrrr r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x17 (0x37) ? ? ? ? ? ocf2b ocf2a tov2 tifr2 read/ w rite rrrrrr/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
194 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? tov2: timer/counter2 overflow flag the tov2 bit is set (one) when an overflow occu rs in timer/counter2. tov2 is cleared by hard- ware when executing the corresponding interrupt handling vector. alternatively, tov2 is cleared by writing a logic one to the flag. w hen the sreg i-bit, toie2a (timer/counter2 overflow inter- rupt enable), and tov2 are set (one), the timer/ counter2 overflow interrupt is executed. in p w m mode, this bit is set when timer/counter2 changes counting direction at 0x00. 20.10.9 gtccr ? general time r/counter control register ? bit 1 ? psrasy: prescaler reset timer/counter2 w hen this bit is one, the time r/counter2 prescaler will be rese t. this bit is normally cleared immediately by hardware. if the bit is written wh en timer/counter2 is operating in asynchronous mode, the bit will remain one until the presca ler has been reset. the bit will not be cleared by hardware if the tsm bit is set. refer to the description of the ?bit 7 ? tsm: timer/counter syn- chronization mode? on page 170 for a description of the timer/counter synchronization mode. bit 7 6 5 4 3 2 1 0 0x23 (0x43) tsm ? ? ? ? ? psrasy psrsync gtccr read/ w rite r/ w rr rrrr/ w r/ w initial value 0 0 0 0 0 0 0 0
195 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 21. spi ? serial peripheral interface the serial peripheral interface (spi) allows hi gh-speed synchronous data transfer between the atmega640/1280/1281/2560/2561 and peripheral devices or between several avr devices. the atmega640/1280/1281/2560/2561 spi includes the following features: ? full-duplex, three-wire synchronous data transfer ? master or slave operation ? lsb first or msb first data transfer ? seven programmable bit rates ? end of transmission interrupt flag ? write collision flag protection ? wake-up from idle mode ? double speed (ck/2) master spi mode usart can also be used in master spi mode, see ?usart in spi mode? on page 232 . the power reduction spi bit, prspi, in ?prr0 ? power reduction register 0? on page 56 on page 50 must be written to zero to enable spi module. figure 21-1. spi block diagram (1) n ote: 1. refer to figure 1-1 on page 2 , and table 13-6 on page 79 for spi pin placement. the interconnection between master and slave cpus with spi is shown in figure 21-2 on page 196 . the system consists of two shift registers, and a master clock generator. the spi master initiates the communication cycle wh en pulling low the slave select ss pin of the desired slave. spi2x spi2x divider /2/4/ 8 /16/32/64/12 8
196 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 master and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from master to slave on the master out ? slave in, mosi, line, and from slave to master on the master in ? slave out, miso, line. after each data packet, the master will synchronize the slave by pulling high the slave select, ss , line. w hen configured as a master, the spi interface has no automatic control of the ss line. this must be handled by user software before communication can start. w hen this is do ne, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the eight bits into the slave. after shifting one byte , the spi clock generator stops, setting the end of transmission flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the buffer register for later use. w hen configured as a slave, the spi interface will remain sleeping with miso tri-stated as long as the ss pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 21-2. spi master-slave interconnection the system is single buffered in the transmit di rection and double buffered in the receive direc- tion. this means that bytes to be transmitted cannot be written to the spi data register before the entire shift cycle is completed. w hen receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. oth- erwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming signal of the sck pin. to ensure correct sampling of the clock signal, the minimum low and high periods should be: low period: longer than 2 cpu clock cycles. high period: longer than 2 cpu clock cycles. w hen the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overridden according to table 21-1 . for more details on automatic port overrides, refer to ?alternate port s hift enable
197 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 functions? on page 75 . n ote: 1. see ?alternate functions of port b? on page 79 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initialize the spi as a master and how to perform a simple transmission. ddr_spi in the examples mu st be replaced by the actual data direction register controlling the spi pins. dd_mosi, dd_miso and dd_sck must be replaced by the actual data direction bits for these pins. for example, if mosi is placed on pin pb5, replace dd_mosi with ddb5 and ddr_spi with ddrb. table 21-1. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input
198 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 199 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the following code examples show how to initialize the spi as a slave and how to perform a simple reception. n ote: 1. see ?about code examples? on page 11. assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 200 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 21.1 ss pin functionality 21.1.1 slave mode w hen the spi is configured as a slave, the slave select (ss ) pin is always input. w hen ss is held low, the spi is activated, and miso becomes an output if configured so by the user. all other pins are inputs. w hen ss is driven high, all pins are inputs, and the spi is passive, which means that it will not receive incoming data. n ote that the spi logic will be reset once the ss pin is driven high. the ss pin is useful for packet/byte synchroniza tion to keep the slave bit counter synchronous with the master clock generator. w hen the ss pin is driven high, the spi slave will immediately reset the send and receive logic, and drop any partially received data in the shift register. 21.1.2 master mode w hen the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if ss is configured as an output, the pin is a general output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be held high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is configured as a master with the ss pin defined as an input, the spi syst em interprets this as another master selecting the spi as a slave and starting to send data to it. to avoid bus contention, the spi system takes the following actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if the spi interrupt is enabled, an d the i-bit in sreg is set, the interrupt routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exists a possi- bility that ss is driven low, the interrup t should always check that the mstr bit is still set. if the mstr bit has been cleared by a slave select, it must be set by the user to re-enable spi master mode. 21.1.3 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in figure 21-3 on page 201 and figure 21-4 on page 201 . data bits are shifted out and latched in on opposite edges of the sck signal, ensuring sufficient time for data signals to stabilize. this is clearly seen by summarizing table 21-3 on page 202 and table 21-4 on page 202 in table 21-2 . table 21-2. cpol functionality leading edge trailing edge spi mode cpol=0, cpha=0 sample (rising) setup (falling) 0 cpol=0, cpha=1 setup (rising) sample (falling) 1 cpol=1, cpha=0 sample (falling) setup (rising) 2 cpol=1, cpha=1 setup (falling) sample (rising) 3
201 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 21-3. spi transfer format with cpha = 0 figure 21-4. spi transfer format with cpha = 1 bit 1 bit 6 l s b m s b s ck (cpol = 0) mode 0 s ample i mo s i/mi s o change 0 mo s i pin change 0 mi s o pin s ck (cpol = 1) mode 2 ss m s b l s b bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 m s b first (dord = 0) l s b first (dord = 1) s ck (cpol = 0) mode 1 s ample i mo s i/mi s o change 0 mo s i pin change 0 mi s o pin s ck (cpol = 1) mode 3 ss m s b l s b bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 bit 1 bit 6 l s b m s b m s b first (dord = 0) l s b first (dord = 1)
202 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 21.2 register description 21.2.1 spcr ? spi control register ? bit 7 ? spie: spi interrupt enable this bit causes the spi in terrupt to be executed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable w hen the spe bit is written to one, the spi is enabled. this bit must be set to enable any spi operations. ? bit 5 ? dord: data order w hen the dord bit is written to one, the lsb of the data word is transmitted first. w hen the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi mode when written logic zero. if ss is configured as an input and is driven low while mstr is set, mstr will be cleared, and spif in spsr will become set. the user will th en have to set mstr to re-enable spi mas- ter mode. ? bit 3 ? cpol: clock polarity w hen this bit is written to one, sck is high when idle. w hen cpol is written to zero, sck is low when idle. refer to figure 21-3 on page 201 and figure 21-4 on page 201 for an example. the cpol functionality is summarized in table 21-3 . ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 21-3 on page 201 and figure 21-4 on page 201 for an example. the cpol functionality is summarized in table 21-4 . bit 76543210 0x2c (0x4c) spie spe dord mstr cpol cpha spr1 spr0 spcr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 table 21-3. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 21-4. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample
203 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the dev ice configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the oscillator clock frequency f osc is shown in table 21-5 . 21.2.2 spsr ? spi status register ? bit 7 ? spif: spi interrupt flag w hen a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is dr iven low when the spi is in master mode, this will also set the spif flag. spif is cleared by hardwa re when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the w col bit is set if the spi data register (s pdr) is written during a data transfer. the w col bit (and the spif bit) are cleared by first reading the spi status register with w col set, and then accessing the spi data register. ? bit 5:1 ? res: reserved bits these bits are reserved bits and will always read as zero. ? bit 0 ? spi2x: double spi speed bit w hen this bit is written logic one the spi s peed (sck frequency) will be doubled when the spi is in master mode (see table 21-5 ). this means that the mini mum sck period will be two cpu clock periods. w hen the spi is configured as slave, the spi is only guaranteed to work at f osc /4 or lower. the spi interface on the atmega640/1280/1281/2560/2561 is also used for program memory and eeprom downloading or uploading. see ?serial downloading? on page 349 for serial pro- gramming and verification. table 21-5. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 000 f osc / 4 001 f osc / 16 010 f osc / 64 011 f osc / 128 100 f osc / 2 101 f osc / 8 110 f osc / 32 111 f osc / 64 bit 76543210 0x2d (0x4d) spifwcol?????spi2xspsr read/ w rite rrrrrrrr/ w initial value00000000
204 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 21.2.3 spdr ? spi data register the spi data register is a read/write register used for data transfer between the register file and the spi shift register. w riting to the register initiates data transmission. reading the regis- ter causes the shift register receive buffer to be read. bit 76543210 0x2e (0x4e) msb lsb spdr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial valuexxxxxxxxundefined
205 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 22. usart 22.1 features ? full duplex operation (independent se rial receive and transmit registers) ? asynchronous or synchronous operation ? master or slave clocked synchronous operation ? high resolution baud rate generator ? supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits ? odd or even parity generation and parity check supported by hardware ? data overrun detection ? framing error detection ? noise filtering includes false start bit detection and digital low pass filter ? three separate interrupts on tx complete, tx data register empty and rx complete ? multi-processor communication mode ? double speed asynchronous communication mode overview the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. the atmega640/1280/2560 has four usart?s, usart0, usart1, usart2, and usart3. the functionality for all four usart?s is de scribed below. usart0, usart1, usart2, and usart3 have different i/o registers as shown in ?register summary? on page 411 . a simplified block diagram of the usart transmitter is shown in figure 22-1 on page 206 . cpu accessible i/o registers and i/o pins are shown in bold. the power reducion usart0 bit, prusart0, in ?prr0 ? power reduction register 0? on page 56 must be disabled by writ ing a logical zero to it. the power reducion usart1 bit, prusart1, in ?prr1 ? power reduction register 1? on page 57 must be disabled by writ ing a logical zero to it. the power reducion usart2 bit, prusart2, in ?prr1 ? power reduction register 1? on page 57 must be disabled by writ ing a logical zero to it. the power reducion usart3 bit, prusart3, in ?prr1 ? power reduction register 1? on page 57 must be disabled by writ ing a logical zero to it.
206 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 22-1. usart block diagram (1) n ote: 1. see figure 1-1 on page 2 , figure 1-3 on page 4 , table 13-12 on page 83 , table 13-15 on page 86 , table 13-24 on page 92 and table 13-27 on page 94 for usart pin placement. the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter and receiver. control registers are shared by all units. the clock generation logic consis ts of synchronization logic fo r external clock input used by synchronous slave operation, and the baud rate generator. the xckn (transfer clock) pin is only used by synchronous transfer mode. the transmi tter consists of a single write buffer, a serial shift register, parity generator and cont rol logic for handling different serial frame for- mats. the write buffer allows a continuous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udrn). the receiver supports the same frame formats as the transmitter, and can detect frame error, data overrun and parity errors. 22.2 clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usartn supports four modes of clock operation: n ormal asynchronous, double speed asyn- chronous, master synchronous and slave synchronous mode. the umseln bit in usart control and status register c (ucsrnc) selects between asynchronous and synchronous operation. double speed (asynchronous mode only) is controlled by the u2xn found in the parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker data bus osc sync logic clock generator transmitter receiver
207 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ucsrna register. w hen using synchronous mode (umseln = 1), the data direction register for the xckn pin (ddr_xckn) controls whether the clock source is internal (master mode) or external (slave mode). the xckn pin is only active when using synchronous mode. figure 22-2 shows a block diagram of the clock generation logic. figure 22-2. clock generation logic, block diagram signal description: txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. f osc xtal pin frequency (system clock). 22.2.1 internal clock generation ? the baud rate generator internal clock generation is used for the as ynchronous and the synchronous master modes of operation. the description in this section refers to figure 22-2 . the usart baud rate register (ubrrn) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at system clock (f osc ), is loaded with the ubrrn value each time the counter has counted down to zero or when the ubrrln register is written. a clock is gene rated each time the counter reaches zero. this clock is the baud rate generator clock output (= f osc /(ubrrn+1)). the transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. the baud rate generator out- put is used directly by the receiver?s clock an d data recovery units. however, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the umseln, u2xn and ddr_xckn bits. table 22-1 on page 208 contains equations for calculating th e baud rate (in bits per second) and for calculating the ubrrn value for each mode of operation using an internally generated clock source. prescaling down-counter /2 ubrr /4 /2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxclk 0 1 1 0 edge detector ucpol
208 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. the baud rate is defined to be the transfer rate in bit per second (bps). baud baud rate (in bits per second, bps). f osc system oscillator clock frequency. ubrrn contents of the ubrrhn and ubrrln registers, (0-4095). some examples of ubrrn values for some system clock frequencies are found in table 22-9 on page 227 . 22.2.2 double speed operation (u2xn) the transfer rate can be doubled by setting the u2xn bit in ucsrna. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the divisor of the baud rate divider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. n ote however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. 22.2.3 external clock external clocking is used by the synchronous sl ave modes of operation. the description in this section refers to figure 22-2 on page 207 for details. external clock input from the xckn pin is sample d by a synchronization register to minimize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process intro- table 22-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous n ormal mode (u2xn = 0) asynchronous double speed mode (u2xn = 1) synchronous master mode baud f osc 16 ubrr n 1 + () ----------------------------------------- - = ubrr n f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? =
209 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 duces a two cpu clock period delay and therefore the maximum external xckn clock frequency is limited by the following equation: n ote that f osc depends on the stability of the system clock source. it is therefore recommended to add some margin to avoid possible loss of data due to frequency variations. 22.2.4 synchronous clock operation w hen synchronous mode is used (umseln = 1), the xckn pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. the basic principle is that data input (on rxdn) is sampled at the opposite xckn clock edge of the edge the data output (txdn) is changed. figure 22-3. synchronous mode xckn timing. the ucpoln bit ucrsc selects which xckn cloc k edge is used for data sampling and which is used for data change. as figure 22-3 shows, when ucpoln is zero the data will be changed at rising xckn edge and sampled at falling xckn edge. if ucpoln is set, the data will be changed at falling xckn edge and samp led at rising xckn edge. 22.3 frame formats a serial frame is defined to be one character of da ta bits with synchronizat ion bits (start and stop bits), and optionally a parity bi t for error checking. the usart accepts all 30 combinations of the following as valid frame formats: ? 1 start bit ? 5, 6, 7, 8, or 9 data bits ? no, even or odd parity bit ? 1 or 2 stop bits a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with t he most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. w hen a complete frame is transmitted, it can be directly followed by a new frame, or the communication line can be set to an idle (high) state. figure 22-4 on page 210 illustrates the possible combinations of the frame formats. bits inside brackets are optional. f xck f osc 4 ----------- < rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample
210 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 22-4. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. sp stop bit, always high. idle n o transfers on the communication line (rxdn or txdn). an idle line must be high. the frame format used by th e usart is set by the ucszn2:0, upmn1:0 and usbsn bits in ucsrnb and ucsrnc. the receiver a nd transmitter use the same setting. n ote that changing the setting of any of these bits will corrupt a ll ongoing communication for both the receiver and transmitter. the usart character size (ucszn2:0) bits select the number of data bits in the frame. the usart parity mode (upmn1:0) bits enable and set the type of parity bit. the selection between one or two stop bits is done by the usart stop bit select (usbsn) bit. the re ceiver ignores the second stop bit. an fe (f rame error) will theref ore only be detected in the cases where the first stop bit is zero. 22.3.1 parity bit calculation the parity bit is calculated by do ing an exclusive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the parity bit is located between the last data bit and first stop bit of a serial frame. the relation betwee n the parity bit and data bits is as follows: p even parity bit using even parity. p odd parity bit using odd parity. d n data bit n of the character. 22.4 usart initialization the usart has to be initialized before any communication can take place. the initialization pro- cess normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. the txcn flag can be used to check that the transmitter has completed all transfers, and the rxc flag can be used to 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = =
211 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 check that there are no unread data in the receive buffer. n ote that the txcn flag must be cleared before each transmission (before udrn is written) if it is used for this purpose. the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the exampl es assume asynchronous operation using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. n ote: 1. see ?about code examples? on page 11. more advanced initialization routines can be made that include frame format as parameters, dis- able interrupts and so on. however, many appl ications use a fixed setting of the baud and control registers, and for these types of applicati ons the initialization code can be placed directly in the main routine, or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate sts ubrrnh, r17 sts ubrrnl, r16 ldi r16, (1<>8); ubrrl = (unsigned char)ubrr; /* enable receiver and transmitter */ ucsrb = (1< 212 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 22.5 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txe n ) bit in the ucsrnb register. w hen the transmitter is enabled, the normal port operation of the txdn pin is overrid- den by the usart and given the function as t he transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any transmissions. if syn- chronous operation is used, the clock on the xckn pi n will be overridden and used as transmission clock. 22.5.1 sending frames with 5 to 8 data bit a data transmission is initiated by loading the transmit buffer with the data to be transmitted. the cpu can load the transmit buffer by writing to the udrn i/o location. the buffered data in the transmit buffer will be moved to the shift register wh en the shift register is ready to send a new frame. the shift register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. w hen the shift register is loaded with new data, it will transf er one complete frame at the ra te given by the baud register, u2xn bit or by xckn depending on mode of operation. the following code examples show a simple usart transmit function based on polling of the data register empty (udren) flag. w hen using frames with less than eight bits, the most sig- nificant bits written to the udrn are ignored. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16. n ote: 1. see ?about code examples? on page 11. the function simply waits for the transmit buffer to be em pty by checking the udren flag, before loading it wit h new data to be transmitted. if the da ta register empty in terrupt is utilized, the interrupt routine writes the data into the buffer. assembly code example (1) usart_transmit: ; wait for empty transmit buffer lds r17, ucsrna sbrs r17, udren rjmp usart_transmit ; put data (r16) into buffer, sends the data sts udrn,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 213 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 22.5.2 sending frames with 9 data bit if 9-bit characters are used (ucszn = 7), the ninth bit must be written to the txb8 bit in ucs- rnb before the low byte of the character is wr itten to udrn. the following code examples show a transmit function that handles 9-bit characters . for the assembly code, the data to be sent is assumed to be stored in registers r17:r16. n otes: 1. these transmit functions are written to be ge neral functions. they can be optimized if the con- tents of the ucsrnb is static. for example, only the txb8 bit of the ucsrnb register is used after initialization. 2. see ?about code examples? on page 11. the ninth bit can be used for indicating an address frame when using multi processor communi- cation mode or for other protocol handling as for example synchronization. 22.5.3 transmitter flags and interrupts the usart transmitter has two flags that indi cate its state: usart data register empty (udren) and transmit complete (txcn). both flags can be used for generating interrupts. the data register empty (udren) flag indicates whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet be en moved into the shift register. for compat- ibility with future devices, alwa ys write this bit to zero when writing the ucsrna register. assembly code example (1)(2) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrnb,txb8 sbrc r17,0 sbi ucsrnb,txb8 ; put lsb data (r16) into buffer, sends the data sts udrn,r16 ret c code example (1)(2) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 214 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w hen the data register empty interrupt enable ( udrien) bit in ucsrnb is written to one, the usart data register empty inte rrupt will be executed as long as udren is set (provided that global interrupts are enabled). ud ren is cleared by writing udrn. w hen interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to udrn in order to clear udren or disable the data register empty interrupt, otherwise a new interrupt will occur once the in terrupt routin e terminates. the transmit complete (txcn) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location . the txcn flag is usef ul in half-duplex commu- nication interfaces (like the rs-485 standard) , where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. w hen the transmit compete interrupt enable (txcien) bit in ucsrnb is set, the usart transmit complete interrupt will be executed when the txcn flag becomes set (provided that global interrupts are enabled). w hen the transmit complete interrupt is used, the interrupt han- dling routine does not have to clear the txcn fl ag, this is done automatically when the interrupt is executed. 22.5.4 parity generator the parity generator calculates the parity bit for the serial frame data. w hen parity bit is enabled (upmn1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. 22.5.5 disabling the transmitter the disabling of the transmitter (setting the txe n to zero) will not become effective until ongo- ing and pending transmissions are completed, that is, when the transmit shift register and transmit buffer register do not contain data to be transmitted. w hen disabled, the transmitter will no longer override the txdn pin. 22.6 data reception ? the usart receiver the usart receiver is enabled by writing the receive enable (rxe n n) bit in the ucsrnb register to one. w hen the receiver is enabled, the normal pin operation of the rxdn pin is overridden by the usart and given the func tion as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before any serial reception can be done. if synchronous operation is used, the cloc k on the xckn pin will be used as transfer clock. 22.6.1 receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at the baud rate or xckn cl ock, and shifted into the receive shift register until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. w hen the first stop bit is received, that is, a complete serial frame is present in the receive shift register, the contents of the shift register will be moved into the rece ive buffer. the receive buffer can then be read by reading the udrn i/o location. the following code example shows a simple us art receive function based on polling of the receive complete (rxcn) flag. w hen using frames with less than eight bits the most significant bits of the data read from the udrn will be masked to zero. th e usart has to be initialized before the function can be used.
215 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. the function simply waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value. 22.6.2 receiving frames with 9 data bits if 9-bit characters are used (ucszn=7) the ninth bit must be read from the rxb8n bit in ucs- rnb before reading the low bits from the udrn. this rule applies to the fe n, dorn and upen status flags as well. read st atus from ucsrna, then data from udrn. reading the udrn i/o location will change the state of the receive bu ffer fifo and consequ ently the txb8n, fen, dorn and upen bits, which all ar e stored in the fifo, will change. the following code example shows a simple usart receive function that handles both nine bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received lds r17, ucsrna sbrs r17, rxcn rjmp usart_receive ; get and return received data from buffer lds r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsrna & (1< 216 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. the receive function example reads all the i/o r egisters into the register file before any com- putation is done. this gives an optimal receive buffer utilization since the bu ffer location read will be free to accept new data as early as possible. 22.6.3 receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxcn) flag indicates if there are unread data present in the receive buf- fer. this flag is one when unread data exist in the receive buffer, and zero when the receive assembly code example (1) usart_receive: ; wait for data to be received lds r17, ucsrna sbrs r17, rxcn rjmp usart_receive ; get status and 9th bit, then data from buffer lds r18, ucsrna lds r17, ucsrnb lds r16, udrn ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
217 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 buffer is empty (that is, does not contain any unread data). if the receiver is disabled (rxe n n = 0), the receive bu ffer will be flushed and consequently the rxcn bit will become zero. w hen the receive complete interrupt enable (rxcien) in ucsrnb is set, the usart receive complete interrupt will be executed as long as the rxcn flag is se t (provided that global inter- rupts are enabled). w hen interrupt-driven data reception is used, the receive complete routine must read the received data from udrn in order to clear the rxcn flag, otherwise a new inter- rupt will occur once the inte rrupt routine terminates. 22.6.4 receiver error flags the usart receiver has three error flags: frame error (fen), data overrun (dorn) and parity error (upen). all can be accessed by reading ucsrna. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buffering of the error flags, the ucsrna must be read before the receive buffer (udrn), since reading the udrn i/o location change s the buffer read location. another equality for the error flags is that they can not be altered by software doing a write to the flag location. however, all flags must be set to zero when the ucsrna is written for upward compatibility of future usart implementations. n one of the error flags can generate interrupts. the frame error (fen) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fen flag is zero when the stop bit was correctly read (as one), and the fen flag will be one when the stop bit was incorrect (zero). this flag can be used for detecting out-of-sync conditions, detecting break conditions and protocol handling. the fen flag is not affected by the setting of the u sbsn bit in ucsrnc since the receiver ignores all, except for the first, stop bits. for compatibility with future devices, always set this bit to zero when writing to ucsrna. the data overrun (dorn) flag indicates data loss due to a receiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters), it is a new character wait- ing in the receive shift register, and a new start bit is detected. if the dorn flag is set there was one or more serial frame lost between the frame last read from udrn, and the next frame read from udrn. for compatibility wi th future devices, always write this bit to zero when writing to ucsrna. the dorn flag is cleared when t he frame received was successfully moved from the shift register to the receive buffer. the parity error (upen) flag indicates that the next frame in the receive buffer had a parity error when received. if parity check is not enabled the upen bit will always be read zero. for compatibility with future devices, always set this bit to zero when writing to ucsrna. for more details see ?parity bit calculation? on page 210 and ?parity checker? on page 217 . 22.6.5 parity checker the parity checker is active when the high usart parity mode (upmn1) bit is set. type of par- ity check to be performed (odd or even) is selected by the upmn0 bit. w hen enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. the result of the check is stored in the receive buffer together with the received data and stop bits. the parity error (upen) flag can then be read by software to check if the frame had a parity error. the upen bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read.
218 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 22.6.6 disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will ther efore be lost. w hen disabled (that is, the rxe n n is set to zero) the receiver will no longer override th e normal function of the rxdn port pi n. the receiver buffer fifo will be flushed when the receiver is disabled. remaining data in th e buffer will be lost. 22.6.7 flushing the receive buffer the receiver buffer fifo will be flushed when th e receiver is disabled, that is, the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for in stance an error conditi on, read the udrn i/o location until the rxcn flag is cleared. the following code example shows how to flush the receive buffer. n ote: 1. see ?about code examples? on page 11. 22.7 asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchronous data reception. the clock recovery logic is used fo r synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxdn pin. the data recovery logic sam- ples and low pass filters each incoming bit, ther eby improving the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the inter- nal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 22.7.1 asynchronous clock recovery the clock recovery logic synchronizes internal clock to the incoming serial frames. figure 22-5 on page 219 illustrates the sampling process of the start bit of an incoming frame. the sample rate is 16 times the baud rate for n ormal mode, and eight times the baud rate for double speed mode. the horizontal arrows illustrate the sy nchronization variation due to the sampling pro- cess. n ote the larger time variation when using the double speed mode (u2xn = 1) of operation. samples denoted zero are samples done when the rxdn line is idle (that is, no com- munication activity). assembly code example (1) usart_flush: sbis ucsrna, rxcn ret in r16, udrn rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsrna & (1< 219 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 22-5. start bit sampling w hen the clock recovery logic detects a high (idle) to low (start) transition on the rxdn line, the start bit detection sequence is initiated. let sample 1 denote the first zero-sample as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for n ormal mode, and sam- ples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. if two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transition. if however, a valid start bit is detected, the clock recov- ery logic is synchronized and the data recove ry can begin. the sy nchronization process is repeated for each start bit. 22.7.2 asynchronous data recovery w hen the receiver clock is synchronized to the start bit, the data recovery can begin. the data recovery unit uses a state machine that has 16 states for each bit in n ormal mode and eight states for each bit in double speed mode. figure 22-6 shows the sampling of the data bits and the parity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 22-6. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majori ty voting of the logic value to the three samples in the center of the received bit. the center samples are emphasized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all three samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxdn pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. n ote that the receiver only uses the first stop bit of a frame. figure 22-7 on page 220 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. 1234567 8 9 10 11 12 13 14 15 16 12 start idle 0 0 bit 0 3 123 4 5 678 12 0 rxd sample (u2x = 0) sample (u2x = 1) 1234567 8 9 10 11 12 13 14 15 16 1 bit n 123 4 5 678 1 rxd sample (u2x = 0) sample (u2x = 1)
220 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 22-7. stop bit sampling and n ext start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 va lue, the frame error (fen) flag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for n ormal speed mode, the first low level sample can be at point marked (a) in figure 22-7 . for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the ear ly start bit detection influences the operational range of the receiver. 22.7.3 asynchronous operational range the operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see table 22-2 on page 221 ) base frequency, the receiver will not be able to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. d sum of character size and parity size (d = 5 to 10 bit). s samples per bit. s = 16 for n ormal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ - = r fast d 2 + () s d 1 + () ss m + ----------------------------------- =
221 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 22-2 and table 22-3 list the maximum receiver baud rate error that can be tolerated. n ote that n ormal speed mode has higher toleration of baud rate variations. the recommendations of the maximum receiver baud rate error was made under the assump- tion that the receiver and transmitter equally divides the maximum total error. there are two possible sources fo r the receivers baud rate erro r. the receiver?s system clock (xtal) will always have some minor instabilit y over the supply voltage range and the tempera- ture range. w hen using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the b aud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. 22.8 multi-processor communication mode setting the multi-processor communication m ode (mpcmn) bit in ucsrna enables a filtering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put in to the receive buffer. this effectively reduces the number of incoming frames that has to be handled by the cpu, in a system with multiple mcus that communicate via the same serial bu s. the transmitter is unaffected by the mpcmn setting, but has to be used diffe rently when it is a part of a system utilizing the multi-processor communication mode. if the receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indi- cates if the frame contains data or address information. if the receiver is set up for frames with table 22-2. recommended maximum receiver baud rate error for n ormal speed mode (u2xn = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11/-5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 22-3. recommended maximum receiver baud rate error for double speed mode (u2xn = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104.35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
222 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 nine data bits, then the ninth bit (rxb8n) is used for identifying address and data frames. w hen the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. w hen the frame type bit is zero the frame is a data frame. the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slave mcu has been addressed, it will rece ive the following data frames as normal, while the other slave mcus will ignore the received frames until another address frame is received. 22.8.1 using mpcmn for an mcu to act as a master mcu, it can us e a 9-bit character frame format (ucszn = 7). the ninth bit (txb8n) must be set when an address frame (txb8n = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communication mode: 1. all slave mcus are in multi-processor communication mode (mpcmn in ucsrna is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxcn flag in ucsrna will be set as normal. 3. each slave mcu reads the udrn register and determines if it has been selected. if so, it clears the mpcmn bit in ucsrna, otherwise it waits for the next address byte and keeps the mpcmn setting. 4. the addressed mcu will receive all data frames until a new address frame is received. the other slave mcus, which still have the mp cmn bit set, will ignore the data frames. 5. w hen the last data frame is received by the addressed mcu, the addressed mcu sets the mpcmn bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5-bit to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full- duplex operation difficult since the transmitter a nd receiver uses the same character size set- ting. if 5-bit to 8-bit character frames are used, the transmitter must be set to use two stop bit (usbsn = 1) since the first stop bit is used for indicating the frame type. do not use read-modify- w rite instructions (sbi and cbi) to set or clear the mpcmn bit. the mpcmn bit shares the same i/o location as the txcn flag and this might accidentally be cleared when using sbi or cbi instructions. 22.9 register description the following section describes the usart?s registers. 22.9.1 udrn ? usart i/o data register n bit 76543210 rxb[7:0] udrn (read) txb[7:0] udrn (write) read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
223 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the usart transmit data buffer register and usart receive data buffer registers share the same i/o address re ferred to as usart data register or udrn. the transmit data buffer reg- ister (txb) will be the destination for data wri tten to the udrn register location. reading the udrn register location will retu rn the contents of the receiv e data buffer register (rxb). for 5-bit, 6-bit, or 7-bit characters the upper unused bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written when the udren flag in the ucsrna register is set. data written to udrn wh en the udren flag is not set, will be ignored by the usart transmit- ter. w hen data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the transmit shift regist er when the shift register is empty. then the data will be serially transmitted on the txdn pin. the receive buffer consists of a two level fifo . the fifo will change its state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify- w rite instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will change the state of the fifo. 22.9.2 ucsrna ? usart contro l and status register a ? bit 7 ? rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (that is, does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and conse quently the rxcn bit will be come zero. the rxcn flag can be used to generate a receive complete interrupt (see description of the rxcien bit). ? bit 6 ? txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 ? udren: usart data register empty the udren flag indicates if the transmit buff er (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrien bit). udren is set after a reset to indicate that the transmitter is ready. ? bit 4 ? fen: frame error this bit is set if the next character in the receive buffer had a frame error when received, that is, when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive buffer (udrn) is read. the fen bit is zero when the stop bit of received data is one. always set this bit to ze ro when writing to ucsrna. bit 76543210 rxcn txcn udren fen dorn upen u2xn mpcmn ucsrna read/ w rite r r/ w rrrrr/ w r/ w initial value00100000
224 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 3 ? dorn: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two characters), it is a new char acter waiting in the receive shift register, and a new start bit is detected. this bi t is valid until the receive buffer (udrn) is read . always set this bit to zero when writing to ucsrna. ? bit 2 ? upen: usart parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 1 ? u2xn: double the usart transmission speed this bit only has effect for the asynchronous operation. w rite this bit to zero when using syn- chronous operation. w riting this bit to one will reduce the divisor of th e baud rate divider from 16 to 8 effectively dou- bling the transfer rate for asynchronous communication. ? bit 0 ? mpcmn: multi-processor communication mode this bit enables the multi-processor communication mode. w hen the mpcmn bit is written to one, all the incoming frames received by the usart receiver that do not contain address infor- mation will be ignored. the transmitter is unaffe cted by the mpcmn setting. for more detailed information see ?multi-processor communication mode? on page 221 . 22.9.3 ucsrnb ? usart control and status register n b ? bit 7 ? rxcien: rx comp lete interrupt enable n w riting this bit to one enables interrupt on the rxcn flag. a usart rece ive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 ? txcien: tx complete interrupt enable n w riting this bit to one enables interrupt on the txcn flag. a usart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 ? udrien: usart data register empty interrupt enable n w riting this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrien bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 ? rxenn: receiver enable n w riting this bit to one enables the usart receiv er. the receiver will override normal port oper- ation for the rxdn pin when enabled. disab ling the receiver will fl ush the receive buffer invalidating the fen, dorn, and upen flags. bit 76543210 rxcien txcien udrien rxenn txenn ucszn2 rxb8n txb8n ucsrnb read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w rr/ w initial value 0 0 0 0 0 0 0 0
225 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 3 ? txenn: transmitter enable n w riting this bit to on e enables the usart transmitter. th e transmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txe n n to zero) will not become effective until ongoing and pending transmissions are completed, that is, when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. w hen disabled, the transmitter will no longer override the txdn port. ? bit 2 ? ucszn2: character size n the ucszn2 bits combined with the ucszn1:0 bit in ucsrnc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8n: receive data bit 8 n rxb8n is the ninth data bit of the received char acter when operating with serial frames with nine data bits. must be read before reading the low bits from udrn. ? bit 0 ? txb8n: transmit data bit 8 n txb8n is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. must be written before writing the low bits to udrn. 22.9.4 ucsrnc ? usart control and status register n c ? bits 7:6 ? umseln1:0 usart mode select these bits select the mode of operation of the usartn as shown in table 22-4 . n ote: 1. see ?usart in spi mode? on page 232 for full description of the master spi mode (mspim) operation. ? bits 5:4 ? upmn1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmitter will automatically generate and send the parity of th e transmitted data bits within each frame. the bit 7 6 5 4 3 2 1 0 umseln1 umseln0 upmn1 upmn0 usbsn ucszn1 ucszn0 ucpoln ucsrnc read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 1 1 0 table 22-4. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim) (1)
226 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 receiver will generate a parity va lue for the incoming data and co mpare it to th e upmn setting. if a mismatch is detected, the upen flag in ucsrna will be set. ? bit 3 ? usbsn: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucszn1:0: character size the ucszn1:0 bits combined with the ucszn2 bit in ucsrnb sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 0 ? ucpoln: clock polarity this bit is used for synchronous mode only. w rite this bit to zero when asynchronous mode is used. the ucpoln bit sets the relationship between data output change and data input sample, and the synchronous clock (xckn). table 22-5. upmn bits settings upmn1 upmn0 parity mode 00 disabled 01 reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 22-6. usbs bit settings usbsn stop bit(s) 01-bit 12-bit table 22-7. ucszn bits settings ucszn2 ucszn1 ucszn0 character size 000 5-bit 001 6-bit 010 7-bit 011 8-bit 1 0 0 reserved 1 0 1 reserved 1 1 0 reserved 111 9-bit table 22-8. ucpoln bit settings ucpoln transmitted data ch anged (output of txdn pin) received data sampled (input on rxdn pin) 0 rising xckn edge falling xckn edge 1 falling xckn edge rising xckn edge
227 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 22.9.5 ubrrnl and ubrrnh ? usart baud rate registers ? bit 15:12 ? reserved bits these bits are reserved for future use. for compatibility with future devices, these bit must be written to zero when ubrrh is written. ? bit 11:0 ? ubrr11:0: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrh contains the four most significant bits, and the ubrrl contains th e eight least significant bits of the usart baud rate. ongoing transmissions by the transmitter and receiver will be corrupted if th e baud rate is changed. w riting ubrrl will trigger an immediate update of the baud rate prescaler. 22.10 examples of ba ud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asyn- chronous operation can be generated by using the ubrr settings in table 22-9 to table 22-12 on page 231 . ubrr values which yield an actual baud rate differing less than 0.5% from the tar- get baud rate, are bold in the table. higher error ratings are acceptable, but the receiver will have less noise resistance when the error ratings are high, especially for large serial frames (see ?asynchronous operational range? on page 220 ). the error values are calculated using the fol- lowing equation: bit 151413121110 9 8 ? ? ? ? ubrr[11:8] ubrrhn ubrr[7:0] ubrrln 76543210 read/ w rite rrrrr/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 00000000 error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? = table 22-9. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000mhz f osc = 1.8432mhz f osc = 2.0000mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 25 0.2% 51 0.2% 47 0.0% 95 0.0% 51 0.2% 103 0.2% 4800 12 0.2% 25 0.2% 23 0.0% 47 0.0% 25 0.2% 51 0.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0%
228 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. ubrr = 0, error = 0.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k ? ? ? ? ? ? 0 0.0% ? ? ? ? 250k??????????00.0% max. (1) 62.5kbps 125kbps 115.2kbps 2 30.4kbps 125kbps 250kbps table 22-9. examples of ubrrn settings for common ly used oscillator frequencies (continued) baud rate (bps) f osc = 1.0000mhz f osc = 1.8432mhz f osc = 2.0000mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error
229 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. ubrr = 0, error = 0.0% table 22-10. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 3.6864mhz f osc = 4.0000mhz f osc = 7.3728mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k110.0%230.0%120.2%250.2%230.0%470.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m??????????0-7.8% max. (1) 230.4kbps 460.8kbps 250kbps 0. 5mbps 460.8kbps 921.6kbps
230 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. ubrr = 0, error = 0.0% table 22-11. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 8.0000mhz f osc = 11.0592 mhz f osc = 14.7456mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k250.2%510.2%350.0%710.0%470.0%950.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k120.2%250.2%170.0%350.0%230.0%470.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m??00.0%????0-7.8%1-7.8% max. (1) 0.5mbps 1mbps 691.2kbps 1.3824mbps 921.6kbps 1.8432mbps
231 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. ubrr = 0, error = 0.0% table 22-12. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 16.0000mhz f osc = 18.4320mhz f osc = 20.0000mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 416 -0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0% 4800 207 0.2% 416 -0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0% 9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2% 14.4k 68 0.6% 138 -0.1% 79 0.0% 159 0.0% 86 -0.2% 173 -0.2% 19.2k 51 0.2% 103 0.2% 59 0.0% 119 0.0% 64 0.2% 129 0.2% 28.8k 34 -0.8% 68 0.6% 39 0.0% 79 0.0% 42 0.9% 86 -0.2% 38.4k250.2%510.2%290.0%590.0%32-1.4%640.2% 57.6k 16 2.1% 34 -0.8% 19 0.0% 39 0.0% 21 -1.4% 42 0.9% 76.8k120.2%250.2%140.0%290.0%151.7%32-1.4% 115.2k 8 -3.5% 16 2.1% 9 0.0% 19 0.0% 10 -1.4% 21 -1.4% 230.4k 3 8.5% 8 -3.5% 4 0.0% 9 0.0% 4 8.5% 10 -1.4% 250k 3 0.0% 7 0.0% 4 -7.8% 8 2.4% 4 0.0% 9 0.0% 0.5m 1 0.0% 3 0.0% ? ? 4 -7.8% ? ? 4 0.0% 1m00.0%10.0%???????? max. (1) 1mbps 2mbps 1.152mbps 2.304mbps 1.25mbps 2.5mbps
232 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 23. usart in spi mode the universal synchronous and asynchronous serial receiver and transmitter (usart) can be set to a master spi compliant mode of operation. the master spi mode (mspim) has the follow- ing features: ? full duplex, three-wire synchronous data transfer ? master operation ? supports all four spi modes of operation (mode 0, 1, 2, and 3) ? lsb first or msb first data tran sfer (configurable data order) ? queued operation (double buffered) ? high resolution baud rate generator ? high speed operatio n (fxckmax = fck/2) ? flexible interrupt generation 23.1 overview setting both umseln1:0 bits to one enables the usart in mspim logic. in this mode of opera- tion the spi master control logic takes direct control over the usart resources. these resources include the transmitter and receiver shift register and buffers, and the baud rate gen- erator. the parity generator and checker, the data and clock recovery logic, and the rx and tx control logic is disabled. the usart rx and tx control logic is replaced by a common spi transfer control logic. however, the pin control l ogic and interrupt generation logic is identical in both modes of operation. the i/o register locations are the same in both modes. however, some of the functionality of the control registers changes when using mspim. 23.2 usart mspim vs. spi the avr usart in mspim mode is fully compatible with the avr spi regarding: ? master mode timing diagram ? the ucpoln bit functionality is identical to the spi cpol bit ? the ucphan bit functionality is identical to the spi cpha bit ? the udordn bit functionality is identical to the spi dord bit however, since the usart in mspim mode reuses the usart resources, the use of the usart in mspim mode is somewhat different compared to the spi. in addition to differences of the control register bits, and that only master operation is supported by the usart in mspim mode, the following features differ between the two modules: ? the usart in mspim mode includes (double) buffering of the transmitter. the spi has no buffer ? the usart in mspim mode receiver includes an additional buffer level ? the spi w col ( w rite collision) bit is not incl uded in usart in mspim mode ? the spi double speed mode (spi2x) bit is not included. however, the same effect is achieved by setting ubrrn accordingly ? interrupt timing is not compatible ? pin control differs due to the master only operation of the usart in mspim mode
233 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 a comparison of the usart in mspim mode and the spi pins is shown in table 23-4 on page 240 . 23.2.1 clock generation the clock generation logic generates the base clock for the transmitter and receiver. for usart mspim mode of operation only internal cl ock generation (that is, master operation) is supported. the data direction register for the xckn pin (ddr_xckn) must therefore be set to one (that is, as output) for the usart in mspim to operate correctly. preferably the ddr_xckn should be set up before the usart in mspim is enabled (that is, txe n n and rxe n n bit set to one). the internal clock generation used in mspim mode is identical to the usart synchronous mas- ter mode. the baud rate or ubrrn setting can therefore be calculated using the same equations, see table 23-1 . n ote: 1. the baud rate is defined to be the transfer rate in bit per second (bps). baud baud rate (in bits per second, bps). f osc system oscillator clock frequency. ubrrn contents of the ubrrnh and ubrrnl registers, (0-4095). 23.3 spi data modes and timing there are four combinations of xckn (sck) phase and polarity with respect to serial data, which are determined by control bits ucphan and ucpoln. the data transfer timing diagrams are shown in figure 23-1 on page 234 . data bits are shifted out and latched in on opposite edges of the xckn signal, ensuring sufficient time for data signals to stabilize. the ucpoln and ucphan functionality is summarized in table 23-2 . n ote that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. table 23-1. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrrn value synchronous master mode baud f osc 2 ubrr n 1 + () -------------------------------------- - = ubrr n f osc 2 baud -------------------- 1 ? = table 23-2. ucpoln and ucphan functionality- ucpoln ucphan spi mode lead ing edge trailing edge 0 0 0 sample (rising) setup (falling) 0 1 1 setup (rising) sample (falling) 1 0 2 sample (falling) setup (rising) 1 1 3 setup (falling) sample (rising)
234 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 23-1. ucphan and ucpoln data transfer timing diagrams. 23.4 frame formats a serial frame for the mspim is defined to be one character of 8 data bits. the usart in mspim mode has two valid frame formats: ? 8-bit data with msb first ? 8-bit data with lsb first a frame starts with the least or most significant data bit. then the next data bits, up to a total of eight, are succeeding, ending with the most or least significant bit accordingly. w hen a complete frame is transmitted, a new frame can directly follow it, or the communication line can be set to an idle (high) state. the udordn bit in ucsrnc sets the frame form at used by the usart in mspim mode. the receiver and transmitter use the same setting. n ote that changing the setting of any of these bits will corrupt all ongoin g communication for both th e receiver and transmitter. 16-bit data transfer can be achieved by writing two data bytes to udrn. a uart transmit com- plete interrupt will then signal that the 16-bit value ha s been shifted out. 23.4.1 usart mspim initialization the usart in mspim mode has to be initialized before any communication can take place. the initialization process normally consists of setting the baud rate, setting master mode of operation (by setting ddr_xckn to one), setting frame format and enabling the transmitter and the receiver. only the transmitter can operate independently. for interrupt driven usart opera- tion, the global interrupt flag should be clear ed (and thus interrupts globally disabled) when doing the initialization. n ote: to ensure immediate initialization of the xckn output the baud-rate register (ubrrn) must be zero at the time the transmitter is enabled. contrary to the normal mode usart operation the ubrrn must then be written to the desired value after the transmitter is enabled, but before the first transmission is started. setting ubrrn to ze ro before enabling the transmitter is not neces- sary if the initialization is done immediatel y after a reset since ubrrn is reset to zero. before doing a re-initialization with changed baud rate, data mode, or frame format, be sure that there is no ongoing transmissions during the per iod the registers are changed. the txcn flag can be used to check that the transmitter has completed all transfers, and the rxcn flag can be used to check that there are no unread data in the receive buffer. n ote that the txcn flag must be cleared bef ore each transmission (before udrn is wri tten) if it is used for this purpose. xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) ucpol=0 ucpol=1 ucpha=0 ucpha=1
235 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the following simple usart initialization code examples show one assembly and one c func- tion that are equal in functionality. the examples assume polling (no interrupts enabled). the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. n ote: 1. see ?about code examples? on page 11. assembly code example (1) usart_init: clr r18 out ubrrnh,r18 out ubrrnl,r18 ; setting the xckn port pin as output, enables master mode. sbi xckn_ddr, xckn ; set mspi mode of operation and spi data mode 0. ldi r18, (1< 236 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 23.5 data transfer using the usart in mspi mode requires the transmitter to be enabled, that is, the txe n n bit in the ucsrnb register is set to one. w hen the transmitter is enabled, the normal port operation of the txdn pin is overridden and given the func tion as the transmitter's serial output. enabling the receiver is optional and is done by setting the rxe n n bit in the ucsrnb register to one. w hen the receiver is enabled, the normal pin operation of the rxdn pin is overridden and given the function as the receiver's se rial input. the xckn will in both cases be used as the transfer clock. after initialization the usart is re ady for doing data transfers. a data transfer is initiated by writ- ing to the udrn i/o location. this is the ca se for both sending and receiving data since the transmitter controls the transfer clock. the data written to udrn is moved from the transmit buf- fer to the shift register when the shift register is ready to send a new frame. n ote: to keep the input buffer in sync with the number of data bytes transmitted, the udrn register must be read once for each byte transmitted. the input buffer operation is identical to normal usart mode, that is, if an overflow occurs the character last received will be lost, not the first data in the buffer. this means that if four bytes are transferr ed, byte 1 first, then byte 2, 3, and 4, and the udrn is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte 1. the following code examples show a simple u sart in mspim mode transfer function based on polling of the data register empty (udren) flag and the receive complete (rxcn) flag. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stor ed in register r16 and the data received will be available in the same register (r16) after the function returns. the function simply waits for the transmit buffer to be em pty by checking the udren flag, before loading it with new data to be transmitted. the function then waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value.
237 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. see ?about code examples? on page 11. 23.5.1 transmitter and receiver flags and interrupts the rxcn, txcn, and udren flag s and corresponding interrupt s in usart in mspim mode are identical in function to the normal usart operation. however, the receiver error status flags (fe, dor, and pe) are not in use and is always read as zero. 23.5.2 disabling the transmitter or receiver the disabling of the transmitter or receiver in usart in mspim mode is identical in function to the normal usart operation. 23.6 usart mspim r egister description the following section describes the registers used for spi operation using the usart. 23.6.1 udrn ? usart mspi m i/o data register the function and bit description of the usart data register (udrn) in mspi mode is identical to normal usart operation. see ?udrn ? usart i/o data register n? on page 222. assembly code example (1) usart_mspim_transfer: ; wait for empty transmit buffer sbis ucsrna, udren rjmp usart_mspim_transfer ; put data (r16) into buffer, sends the data out udrn,r16 ; wait for data to be received usart_mspim_wait_rxcn: sbis ucsrna, rxcn rjmp usart_mspim_wait_rxcn ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 238 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 23.6.2 ucsrna ? usart mspim control and status register n a ? ? bit 7 - rxcn: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (that is, does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and conse quently the rxcn bit will be come zero. the rxcn flag can be used to generate a receive complete interrupt (see description of the rxcien bit). ? bit 6 - txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udrn). the txcn flag bit is auto- matically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag can generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 - udren: usart data register empty the udren flag indicates if the transmit buff er (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generate a data register empty interrupt (see description of the udrie bit). udren is set after a reset to indicate that the tr ansmitter is ready. ? bit 4:0 - reserved bits in mspi mode w hen in mspi mode, these bits are reserved for future use. for compatib ility with future devices, these bits must be written to zero when ucsrna is written. 23.6.3 ucsrnb ? usart mspim control and status register n b ? bit 7 - rxcien: rx complete interrupt enable w riting this bit to one enables interrupt on the rxcn flag. a usart rece ive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 - txcien: tx complete interrupt enable w riting this bit to one enables interrupt on the txcn flag. a usart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. bit 7 6 5 4 3 2 1 0 rxcn txcn udren - - - - - ucsrna read/ w rite r/ w r/ w r/ w rr r r r initial value 0 0 0 0 0 1 1 0 bit 7 6543210 rxcien txcien udrie rxenn txenn - - - ucsrnb read/ w rite r/ w r/ w r/ w r/ w r/ w rrr initial value 0 0 0 0 0 1 1 0
239 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 5 - udrie: usart data re gister empty interrupt enable w riting this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrie bit is written to one, the glob al interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 - rxenn: receiver enable w riting this bit to one enables the usart rece iver in mspim mode. the receiver will override normal port oper ation for the rxdn pin when enabled . disabling the receiver will flush the receive buffer. only enabling the receiver in mspi mode (that is, setting rxe n n=1 and txe n n=0) has no meaning since it is the transmitte r that controls the transfer clock and since only master mode is supported. ? bit 3 - txenn: transmitter enable w riting this bit to on e enables the usart transmitter. th e transmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txe n n to zero) will not become effective until ongoing and pending transmissions are completed, that is, when the transmit shift register and transmit buffer register do not contain data to be trans- mitted. w hen disabled, the transmitter will no longer override the txdn port. ? bit 2:0 - reserved bits in mspi mode w hen in mspi mode, these bits are reserved for future use. for compatib ility with future devices, these bits must be written to zero when ucsrnb is written. 23.6.4 ucsrnc ? usart mspim control and status register n c ? bit 7:6 - umseln1:0: usart mode select these bits select the mode of operation of the usart as shown in table 23-3 . see ?ucsrnc ? usart control and status register n c? on page 225 for full description of the normal usart operation. the mspim is enabled when both umseln bits are set to one. the udordn, ucphan, and ucpoln can be set in the same write operation where the mspim is enabled. ? bit 5:3 - reserved bits in mspi mode w hen in mspi mode, these bits are reserved for future use. for compatib ility with future devices, these bits must be written to zero when ucsrnc is written. bit 7 6 543 2 1 0 umseln1 umseln0 - - - udordn ucphan ucpoln ucsrnc read/ w rite r/ w r/ w rrr r/ w r/ w r/ w initial value 0 0 0 0 0 1 1 0 table 23-3. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim)
240 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 2 - udordn: data order w hen set to one the lsb of the data word is transmitted first. w hen set to zero the msb of the data word is transmitted first. refer to ?spi data modes and timing? on page 233 for details. ? bit 1 - ucphan: clock phase the ucphan bit setting determine if data is sampled on the leasing edge (first) or tailing (last) edge of xckn. refer to ?spi data modes and timing? on page 233 for details. ? bit 0 - ucpoln: clock polarity the ucpoln bit sets the polarity of the xc kn clock. the combination of the ucpoln and ucphan bit settings determine the timing of the data transfer. refer to ?spi data modes and timing? on page 233 for details. 23.6.5 ubrrnl and ubrrnh ? usart mspim baud rate registers the function and bit description of the baud rate registers in mspi mode is identical to normal usart operation. see ?ubrrnl and ubrrnh ? usart baud rate registers? on page 227. table 23-4. comparison of usart in mspim mode and spi pins. usart_mspim spi comment txdn mosi master out only rxdn miso master in only xckn sck (functionally identical) ( n /a) ss n ot supported by usart in mspim
241 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24. 2-wire serial interface 24.1 features ? simple yet powerful and flexible communication interface, only two bus lines needed ? both master and sla ve operation supported ? device can operate as transmitter or receiver ? 7-bit address space allows up to 128 different slave addresses ? multi-master arbitration support ? up to 400khz data transfer speed ? slew-rate limited output drivers ? noise suppression circuitry rejects spikes on bus lines ? fully programmable slave address with general call support ? address recognition causes wake-up when avr is in sleep mode 24.2 2-wire serial in terface bus definition the 2-wire serial interface (t w i) is ideally suited for typica l microcontroller applications. the t w i protocol allows the systems designer to inte rconnect up to 128 different devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hard- ware needed to implement the bus is a single pull-up resistor for each of the t w i bus lines. all devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the t w i protocol. figure 24-1. t w i bus interconnection 24.2.1 twi terminology the following definitions are frequently encountered in this section. device 1 device 2 device 3 device n sda scl ........ r1 r2 v cc table 24-1. t w i terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock slave the device addressed by a master transmitter the device placing data on the bus receiver the device reading data from the bus
242 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the power reduction t w i bit, prt w i bit in ?prr0 ? power reduction register 0? on page 56 must be written to zero to enable the 2-wire serial interface. 24.2.2 electrical interconnection as depicted in figure 24-1 on page 241 , both bus lines are connected to the positive supply volt- age through pull-up resistors. the bus drivers of all t w i-compliant devices are open-drain or open-collector. this implements a wired-a n d function which is essential to the operation of the interface. a low level on a t w i bus line is generated when one or more t w i devices output a zero. a high level is output when all t w i devices trim-state their outputs, allowing the pull-up resistors to pull the line high. n ote that all avr devices connected to the t w i bus must be pow- ered in order to allow any bus operation. the number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400pf and the 7-bit slave address space. a detailed specification of the electrical charac- teristics of the t w i is given in ?spi timing characteristics? on page 375 . two different sets of specifications are presented ther e, one relevant for bus speeds below 100khz, and one valid for bus speeds up to 400khz. 24.3 data transfer and frame format 24.3.1 transferring bits each data bit transferred on the t w i bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generating start and stop conditions. figure 24-2. data validity 24.3.2 start and stop conditions the master initiates and terminates a data transmi ssion. the transmission is initiated when the master issues a start condition on the bus, and it is terminated when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should try to seize control of the bus. a special case occurs when a new start condition is issued between a start and stop condition. this is referred to as a repeated start condition, and is used when the master wis hes to initiate a new transfer without relin- quishing control of the bus. after a repeated start, the bus is considered busy until the next stop. this is identical to the start behavior, and therefore start is used to describe both start and repeated start for the remainder of this datasheet, unless otherwise noted. as depicted below, start and stop conditions are signalled by changing the level of the sda line when the scl line is high. sda scl data stable data stable data change
243 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-3. start, repeated start and stop conditions 24.3.3 address packet format all address packets transmitted on the t w i bus are 9 bits long, consisting of 7 address bits, one read/ w rite control bit and an acknowledge bit. if the read/ w rite bit is set, a read opera- tion is to be performed, otherwise a write operation should be performed. w hen a slave recognizes that it is being a ddressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycle. if the addressed slave is busy, or for some other reason can not service the mas- ter?s request, the sda line should be left high in the ack clock cycle. the master can then transmit a stop condition, or a repeated start condition to initiate a new transmission. an address packet consisting of a slave address and a read or a w rite bit is called sla+r or sla+ w , respectively. the msb of the address byte is transmitted first. slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. w hen a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wi shes to transmit the same message to several slaves in the system. w hen the general call address followed by a w rite bit is transmitted on the bus, all slaves set up to ackn owledge the general call will pull th e sda line low in the ack cycle. the following data packets will then be received by all the slaves that acknowle dged the general call. n ote that transmitting the general call address followed by a read bit is meaningless, as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx should be reserved for future purposes. figure 24-4. address packet format sda scl start stop repeated start stop start sda scl start 12 789 addr msb addr lsb r/w ack
244 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24.3.4 data packet format all data packets transmitted on the t w i bus are nine bits long, consisting of one data byte and an acknowledge bit. during a data transfer, the master generates the clock and the start and stop conditions, while the receiver is res ponsible for acknowledging the reception. an acknowledge (ack) is signalled by the receiver pulling the sda line low during the ninth scl cycle. if the receiver leaves the sda line high, a n ack is signalled. w hen the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a n ack after the final byte. the msb of the data byte is transmitted first. figure 24-5. data packet format 24.3.5 combining address and data packets into a transmission a transmission basically consists of a start condition, a sla+r/ w , one or more data packets and a stop condition. an empty message, consisting of a start followed by a stop condi- tion, is illegal. n ote that the w ired-a n ding of the scl line can be used to implement handshaking between the master and the slave. the slave can extend the scl low period by pulling the scl line low. this is useful if the cloc k speed set up by the master is too fast for the slave, or the slave needs extra time for proces sing between the data transmissions. the slave extending the scl low period will not affect t he scl high period, which is determined by the master. as a consequence, the slave can reduce the t w i data transfer speed by prolonging the scl duty cycle. figure 24-6 shows a typical data transmission. n ote that several data bytes can be transmitted between the sla+r/ w and the stop condition, depending on the software protocol imple- mented by the application software. figure 24-6. typical data transmission 12 789 data msb data lsb ack aggregate sda sda from transmitter sda from receiver scl from master sla+r/w data byte stop, repeated start or next data byte 12 789 data byte data msb data lsb ack sda scl start 12 789 addr msb addr lsb r/w ack sla+r/w stop
245 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24.4 multi-master bus systems, arbitration and synchronization the t w i protocol allows bus systems with severa l masters. special concerns have been taken in order to ensure that transmis sions will proceed as normal, even if two or more masters initiate a transmission at the same time. two problems arise in multi-master systems: ? an algorithm must be implemented allowing only one of the masters to complete the transmission. all other masters should cease tr ansmission when they discover that they have lost the selection process. this selection process is called arbitration. w hen a contending master discovers that it has lost the arbitration process, it should immediately switch to slave mode to check whether it is being addressed by the winning master. the fact that multiple masters have started transmission at the same time should not be detectable to the slaves, that is, the data being transferred on the bus must not be corrupted. ? different masters may use different scl frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. this will fac ilitate the arbitration process. the wired-a n ding of the bus lines is used to solve both these problems. the serial clocks from all masters will be wired-a n ded, yielding a combined clock with a high period equal to the one from the master with the shortest high period. the low period of the combined clock is equal to the low period of the master with the longest low period. n ote that all masters listen to the scl line, effectively starting to count their scl high and low time-out periods when the combined scl line goes high or low, respectively. figure 24-7. scl synchronization betw een multiple masters arbitration is carried out by all masters cont inuously monitoring the sda line after outputting data. if the value read from the sda line does not match the value the master had output, it has lost the arbitration. n ote that a master can only lose arbitration when it outputs a high sda value while another master outputs a low value. the losing master should immediately go to slave mode, checking if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. arbitration will cont inue until only one master re mains, and this may take many bits. if several masters are trying to address th e same slave, arbitratio n will continue into the data packet. ta low ta high scl from master a scl from master b scl bus line tb low tb high masters start counting low period masters start counting high period
246 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-8. arbitration between two masters n ote that arbitration is not allowed between: ? a repeated start cond ition and a data bit ? a stop condition and a data bit ? a repeated start and a stop condition it is the user software?s responsibility to ensur e that these illegal arbitration conditions never occur. this implies that in multi-master systems, all data transfers must use the same composi- tion of sla+r/ w and data packets. in other words: all transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined. 24.5 overview of the twi module the t w i module is comprised of several submodules, as shown in figure 24-9 on page 247 . all registers drawn in a thick line are accessible through the avr data bus. sda from master a sda from master b sda line synchronized scl line start master a loses arbitration, sda a sda
247 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-9. overview of the t w i module 24.5.1 scl and sda pins these pins interface the avr t w i with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the t w i specification. the input stages contain a spike suppression unit removing spikes shorter than 50ns. n ote that the internal pull-ups in the avr pads can be enabled by setting the port bits corresponding to the scl and sda pins, as explained in the i/o port section. the internal pull-ups can in some systems eliminate the need for external ones. 24.5.2 bit rate generator unit this unit controls the period of scl when oper ating in a master mode. the scl period is con- trolled by settings in the t w i bit rate register (t w br) and the prescaler bits in the t w i status register (t w sr). slave operation does not depend on bit rate or prescaler settings, but the cpu clock frequency in the slave must be at least 16 times higher than the scl frequency. n ote that slaves may prolong the scl low period, thereby reducing the average t w i bus clock period. twi unit address register (twar) address match unit address comparator control unit control register (twcr) status register (twsr) state machine and status control scl slew-rate control spike filter sda slew-rate control spike filter bit rate generator bit rate register (twbr) prescaler bus interface unit start / stop control arbitration detection ack spike suppression address/data shift register (twdr)
248 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the scl frequency is generated according to the following equation: ?t w br = value of the t w i bit rate register ?t w ps = value of the prescaler bits in the t w i status register n ote: pull-up resistor values should be selected according to the scl frequency and the capacitive bus line load. see ?2-wire serial interface characteristics? on page 373 for value of pull-up resistor. 24.5.3 bus interface unit this unit contains the data and address shift register (t w dr), a start/stop controller and arbitration detection hardware. the t w dr contains the address or data bytes to be transmitted, or the address or data bytes received. in addition to the 8-bit t w dr, the bus interface unit also contains a register containing the ( n )ack bit to be transmitted or received. this ( n )ack regis- ter is not directly accessible by the application software. however, when re ceiving, it can be set or cleared by manipulating the t w i control register (t w cr). w hen in transmitter mode, the value of the received ( n )ack bit can be determined by the value in the t w sr. the start/stop controller is responsible for gene ration and detection of start, repeated start, and stop conditions. the start/stop controller is able to detect start and stop conditions even when the avr mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the t w i has initiated a transmission as master, the arbitration detection hardware continu- ously monitors the transmission trying to determine if arbitration is in process. if the t w i has lost an arbitration, the control unit is informed. correct action can then be taken and appropriate status codes generated. 24.5.4 address match unit the address match unit checks if received address bytes match the seven-bit address in the t w i address register (t w ar). if the t w i general call recognition enable (t w gce) bit in the t w ar is written to one, all incoming address bi ts will also be compared against the general call address. upon an address match, the control unit is informed, allowing correct action to be taken. the t w i may or may not acknowledge its address, depending on settings in the t w cr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake up if addressed by a master. if another interrupt (for example, i n t0) occurs during t w i power-down address match and wakes up the cpu, the t w i aborts operation and return to it?s idle state. if this cause any problems, ensure that t w i address match is the only enabled interrupt when entering power-down. 24.5.5 control unit the control unit monitors the t w i bus and generates responses corresponding to settings in the t w i control register (t w cr). w hen an event requiring the attention of the application occurs on the t w i bus, the t w i interrupt flag (t w i n t) is asserted. in the next clock cycle, the t w i sta- tus register (t w sr) is updated with a status code identifying the event. the t w sr only contains relevant status information when the t w i interrupt flag is asserted. at all other times, the t w sr contains a special status code indicating t hat no relevant status information is avail- able. as long as the t w i n t flag is set, the scl line is held low. this allows the application software to complete its tasks before allowing the t w i transmission to continue. scl frequency cpu clock frequency 16 2(t w br) 4 twps ? + ----------------------------------------------------------- =
249 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the t w i n t flag is set in th e following situations: ? after the t w i has transmitted a start/repeated start condition ? after the t w i has transmitted sla+r/ w ? after the t w i has transmitted an address byte ? after the t w i has lost arbitration ? after the t w i has been addressed by own slave address or general call ? after the t w i has received a data byte ? after a stop or repeated start has been received while still add ressed as a slave ? w hen a bus error has occurr ed due to an illegal start or stop condition 24.6 using the twi the avr t w i is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmission of a start condition. because the t w i is interrupt-based, the application software is free to carry on other operations during a t w i byte transfer. n ote that the t w i interrupt enable (t w ie) bit in t w cr together with the global interrupt enable bit in sreg allow the application to decide whether or not assertion of the t w i n t flag should gener- ate an interrupt request. if the t w ie bit is cleared, the application must poll the t w i n t flag in order to detect actions on the t w i bus. w hen the t w i n t flag is asserted, the t w i has finished an operation and awaits application response. in this case, the t w i status register (t w sr) contains a value indicating the current state of the t w i bus. the application software can then decide how the t w i should behave in the next t w i bus cycle by manipulating the t w cr and t w dr registers. figure 24-10 is a simple example of how the application can interface to the t w i hardware. in this example, a master wishes to transmit a single data byte to a slave. this description is quite abstract, a more detailed explanation follows later in this section. a simple code example imple- menting the desired behavior is also presented. figure 24-10. interfacing the application to the t w i in a typical transmission start sla+w a data a stop 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla+w sent, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla+w into twdr, and loads appropriate control signals into twcr, makin sure that twint is written to one, and twsta is written to zero. 5. check twsr to see if sla+w was sent and ack received. application loads data into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, making sure that twint is written to one twi bus indicates twint set application action twi hardware action
250 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 1. the first step in a t w i transmission is to transmit a start condition. this is done by writing a specific value into t w cr, instructing the t w i hardware to transmit a start condition. w hich value to write is described later on. however, it is important that the t w i n t bit is set in the value written. w riting a one to t w i n t clears the flag. the t w i will not start any operation as long as the t w i n t bit in t w cr is set. immediately after the application has cleared t w i n t, the t w i will initiate transmission of the start condition. 2. w hen the start condition has been transmitted, the t w i n t flag in t w cr is set, and t w sr is updated with a status code indicating that the start condition has success- fully been sent. 3. the application software should now examine the value of t w sr, to make sure that the start condition was successfully transmitted. if t w sr indicates otherwise, the applica- tion software might take some special action, like calling an error routine. assuming that the status code is as expected, the application must load sla+ w into t w dr. remember that t w dr is used both for address and data. after t w dr has been loaded with the desired sla+ w , a specific value must be written to t w cr, instructing the t w i hardware to transmit the sla+ w present in t w dr. w hich value to write is described later on. however, it is important that the t w i n t bit is set in the value written. w riting a one to t w i n t clears the flag. the t w i will not start any operation as long as the t w i n t bit in t w cr is set. immediately after the application has cleared t w i n t, the t w i will initiate transmission of the address packet. 4. w hen the address packet has been transmitted, the t w i n t flag in t w cr is set, and t w sr is updated with a status code indicating that the address packet has successfully been sent. the status code will also reflect whether a slave acknowledged the packet or not. 5. the application software should now examine the value of t w sr, to make sure that the address packet was successfully transmitted, and that the value of the ack bit was as expected. if t w sr indicates otherwise, the application software might take some special action, like calling an error routine. assuming that the status code is as expected, the application must load a data packet into t w dr. subsequently, a specific value must be written to t w cr, instructing the t w i hardware to transmit the data packet present in t w dr. w hich value to write is described later on. however, it is important that the t w i n t bit is set in the value written. w riting a one to t w i n t clears the flag. the t w i will not start any operation as long as the t w i n t bit in t w cr is set. immediately after the application has cleared t w i n t, the t w i will initiate transmissi on of the data packet. 6. w hen the data packet has been transmitted, the t w i n t flag in t w cr is set, and t w sr is updated with a status code indicating that the data packet has successfully been sent. the status code will also re flect whether a slave ackno wledged the packet or not. 7. the application software should now examine the value of t w sr, to make sure that the data packet was successfully transmitted, and that the value of the ack bit was as expected. if t w sr indicates otherwise, the application software might take some special action, like calling an error routine. assuming that the status code is as expected, the application must write a specific value to t w cr, instructing the t w i hardware to transmit a stop condition. w hich value to write is described late r on. however, it is important that the t w i n t bit is set in th e value written. w riting a one to t w i n t clears the flag. the t w i will not start any operation as long as the t w i n t bit in t w cr is set. immediately after the application has cleared t w i n t, the t w i will initiate transmission of the stop condi- tion. n ote that t w i n t is n ot set after a stop condition has been sent.
251 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 even though this example is simple, it shows the principles involved in all t w i transmissions. these can be summarized as follows: ? w hen the t w i has finished an operation and expects application response, the t w i n t flag is set. the scl line is pulled low until t w i n t is cleared. ? w hen the t w i n t flag is set, the user must update all t w i registers with the value relevant for the next t w i bus cycle. as an example, t w dr must be loaded with the value to be transmitted in the next bus cycle. ? after all t w i register updates and other pending application software tasks have been completed, t w cr is written. w hen writing t w cr, the t w i n t bit should be set. w riting a one to t w i n t clears the flag. the t w i will then commence executin g whatever operation was specified by the t w cr setting. in the following an assembly and c impl ementation of the example is given. n ote that the code below assumes that several definitions have been made, for example by using include-files. assembly code example c example comments 1 ldi r16, (1< 252 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24.7 transmission modes the t w i can operate in one of four major modes. these are named master transmitter (mt), master receiver (mr), slave transmitter (st) and slave receiver (sr). several of these modes can be used in the same application. as an example, the t w i can use mt mode to write data into a t w i eeprom, mr mode to read the data back from the eeprom. if other masters are present in the system, some of these might transmit data to the t w i, and then sr mode would be used. it is the application softw are that decides which modes are legal. the following sections describe each of these modes. possible status codes are described along with figures detailing data transmission in each of the modes. these figures contain the following abbreviations: s: start condition rs: repeated start condition r: read bit (high level at sda) w: w rite bit (low level at sda) a: acknowledge bit (low level at sda) a : n ot acknowledge bit (high level at sda) data: 8-bit data byte p: stop condition sla: slave address in figure 24-12 on page 255 to figure 24-18 on page 264 , circles are used to indicate that the t w i n t flag is set. the numbers in the circles show the status code held in t w sr, with the prescaler bits masked to zero. at these points, ac tions must be taken by the application to con- tinue or complete the t w i transfer. the t w i transfer is suspended until the t w i n t flag is cleared by software. w hen the t w i n t flag is set, the status code in t w sr is used to determine the appropriate soft- ware action. for each status code, the required software action and details of the following serial transfer are given in table 24-2 on page 254 to table 24-5 on page 263 . n ote that the prescaler bits are masked to zero in these tables. 6 wait3: in r16,twcr sbrs r16,twint rjmp wait3 while (!(twcr & (1< 253 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24.7.1 master transmitter mode in the master transmitter mode, a number of data bytes are transmitted to a slave receiver (see figure 24-11 ). in order to enter a master mode, a start condition must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+ w is transmitted, mt mode is entered, if sla+r is trans- mitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 24-11. data transfer in master transmitter mode a start condition is sent by writing the following value to t w cr: t w e n must be set to enable the 2-wire serial interface, t w sta must be written to one to trans- mit a start condition and t w i n t must be written to one to clear the t w i n t flag. the t w i will then test the 2-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the t w i n t flag is set by hardware, and the status code in t w sr will be 0x08 (see table 24-2 on page 254 ). in order to enter mt mode, sla+ w must be transmitted. this is done by writing sla+ w to t w dr. thereafter the t w i n t bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to t w cr: w hen sla+ w have been transmitted and an acknowledgement bit has been received, t w i n t is set again and a number of status codes in t w sr are possible. possible status codes in master mode are 0x18, 0x20, or 0x38. the appropriate action to be taken for each of these status codes is detailed in table 24-2 on page 254 . w hen sla+ w has been successfully transmitted, a data packet should be transmitted. this is done by writing the data byte to t w dr. t w dr must only be written when t w i n t is high. if not, the access will be discarded, and the w rite collision bit (t ww c) will be set in the t w cr regis- ter. after updating t w dr, the t w i n t bit should be cleared (by writing it to one) to continue the transfer. this is acco mplished by writing the following value to t w cr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x device 1 master transmitter device 2 slave receiver device 3 device n sda scl ........ r1 r2 v cc
254 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 this scheme is repeated until the last byte has been sent and the transfer is ended by generat- ing a stop condition or a repeated start condition. a stop condition is generated by writing the following value to t w cr: a repeated start condition is generated by writing the following value to t w cr: after a repeated start condition (state 0x10) th e 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode with- out losing control of the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x table 24-2. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hard- ware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+w 0 0 1 x sla+w will be transmitted; ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+w or load sla+r 0 0 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode 0x18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x28 data byte has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x30 data byte has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode entered a start condition will be transmitted when the bus be- comes free
255 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-12. formats and states in the master transmitter mode 24.7.2 master receiver mode in the master receiver mode, a number of data bytes are received from a slave transmitter (see figure 24-13 on page 256 ). in order to enter a master mode, a start condition must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+ w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. s sla w a data a p $08 $18 $28 r sla w $10 ap $20 p $30 a or a $38 a other master continues a or a $38 other master continues r a $68 other master continues $78 $b0 to corresponding states in slave mode mt mr successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero s
256 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-13. data transfer in ma ster receiver mode a start condition is sent by writing the following value to t w cr: t w e n must be written to one to enable the 2-wire serial interface, t w sta must be written to one to transmit a start condition and t w i n t must be set to clear the t w i n t flag. the t w i will then test the 2-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the t w i n t flag is set by hard- ware, and the status code in t w sr will be 0x08 (see table 24-2 on page 254 ). in order to enter mr mode, sla+r must be transmitted. this is done by writing sla+r to t w dr. thereafter the t w i n t bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to t w cr: w hen sla+r have been transmitted and an acknowledgement bit has been received, t w i n t is set again and a number of status codes in t w sr are possible. possible status codes in master mode are 0x38, 0x40, or 0x48. the appropriate action to be taken for each of these status codes is detailed in table 24-3 on page 257 . received data can be read from the t w dr register when the t w i n t flag is set high by hardware. this scheme is repeated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a n ack after the last received data byte. the transfer is ended by generating a stop condition or a repeated start condition. a stop condition is generated by writing the following value to t w cr: a repeated start condition is generated by writing the following value to t w cr: after a repeated start condition (state 0x10) th e 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode with- out losing control over the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master receiver device 2 slave transmitter device 3 device n sda scl ........ r1 r2 v cc
257 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 24-3. status codes for master receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hard- ware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+r 0 0 1 x sla+r will be transmitted ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+r or load sla+w 0 0 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode 0x38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free 0x40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset
258 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-14. formats and states in the master receiver mode 24.7.3 slave receiver mode in the slave receiver mode, a number of data bytes are received from a master transmitter (see figure 24-15 ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 24-15. data transfer in slave receiver mode to initiate the slave receiver mode, t w ar and t w cr must be initialized as follows: s sla r a data a $08 $40 $50 sla r $10 ap $48 a or a $38 other master continues $38 other master continues w a $68 other master continues $78 $b0 to corresponding states in slave mode mr mt successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p data a $58 a r s twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address device 3 device n sda scl ........ r1 r2 v cc device 2 master transmitter device 1 slave receiver
259 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the upper seven bits are the address to which the 2-wire serial interface will respond when addressed by a master. if the lsb is set, the t w i will respond to the general call address (0x00), otherwise it will ignore the general call address. t w e n must be written to one to enable the t w i. the t w ea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. t w sta and t w sto must be written to zero. w hen t w ar and t w cr have been initialized, the t w i waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the t w i will operate in sr mode, otherw ise st mode is entered. after its own slave address and the write bit have been received, the t w i n t flag is set and a valid status code can be read from t w sr. the status code is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 24-4 on page 260 . the slave receiver mode may also be en tered if arbitration is lost while the t w i is in the master mode (see states 0x68 and 0x78). if the t w ea bit is reset during a transfer, the t w i will return a ? n ot acknowledge? (?1?) to sda after the next received data byte. this can be used to indicate that the slave is not able to receive any more bytes. w hile t w ea is zero, the t w i does not acknowledge its own slave address. however, the 2-wire se rial bus is still monitored and address recognit ion may resume at any time by setting t w ea. this implies that the t w ea bit may be used to temporarily isolate the t w i from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the t w i is turned off. if the t w ea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the 2-wire serial bus clock as a clock sour ce. the part will then wake up from sleep and the t w i will hold the scl clock low duri ng the wake up and until the t w i n t flag is cleared (by writing it to one). further data reception will be carried out as normal, with the avr clocks run- ning as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. n ote that the 2-wire serial interface data register ? t w dr does not reflect the last byte present on the bus when waking up from these sleep modes. twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
260 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 24-4. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0x90 previously addressed with general call; data has been re- ceived; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xa0 a stop condition or repeated start condition has been received while still addressed as slave no action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
261 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-16. formats and states in the slave receiver mode 24.7.4 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure 24-17 ). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 24-17. data transfer in slave transmitter mode s sla w a data a $60 $80 $88 a $68 reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave reception of the general call address and one or more data bytes last data byte received is not acknowledged n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data a $80 $a0 p or s a a data a $70 $90 $98 a $78 p or s data a $90 $a0 p or s a general call arbitration lost as master and addressed as slave by general call data a device 3 device n sda scl ........ r1 r2 v cc device 2 master receiver device 1 slave transmitter
262 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 to initiate the slave transmitter mode, t w ar and t w cr must be initialized as follows: the upper seven bits are the address to which the 2-wire serial interface will respond when addressed by a master. if the lsb is set, the t w i will respond to the general call address (0x00), otherwise it will ignore the general call address. t w e n must be written to one to enable the t w i. the t w ea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. t w sta and t w sto must be written to zero. w hen t w ar and t w cr have been initialized, the t w i waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the t w i will operate in st mode, otherw ise sr mode is entered. after its own slave address and the write bit have been received, the t w i n t flag is set and a valid status code can be read from t w sr. the status code is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 24-5 on page 263 . the slave transmitter mode may also be entered if arbitration is lost while the t w i is in the master mode (see state 0xb0). if the t w ea bit is written to zero during a transfer, the t w i will transmit the last byte of the trans- fer. state 0xc0 or state 0xc8 will be entere d, depending on whether the master receiver transmits a n ack or ack after the final byte. the t w i is switched to the not addressed slave mode, and will ignore the mast er if it continues th e transfer. thus the ma ster receiver receives all ?1? as serial data. state 0xc8 is entered if the master demands additional data bytes (by transmitting ack), even though the slave has transmitted the last byte (t w ea zero and expect- ing n ack from the master). w hile t w ea is zero, the t w i does not respond to its own slave address. however, the 2-wire serial bus is still monitored an d address recognition may resume at any time by setting t w ea. this implies that the t w ea bit may be used to temporarily isolate the t w i from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the t w i is turned off. if the t w ea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the 2-wire serial bus clock as a clock sour ce. the part will then wake up from sleep and the t w i will hold the scl clock will low duri ng the wake up and until the t w i n t flag is cleared (by writing it to one). further data tr ansmission will be carried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. n ote that the 2-wire serial interface data register ? t w dr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
263 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 24-5. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xa8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xc0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xc8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
264 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 24-18. formats and states in the slave transmitter mode 24.7.5 miscellaneous states there are two status codes that do not correspond to a defined t w i state, see table 24-6 . status 0xf8 indicates that no relevant information is available because the t w i n t flag is not set. this occurs between other states, and when the t w i is not involved in a serial transfer. status 0x00 indicates that a bus error has occu rred during a 2-wire serial bus transfer. a bus error occurs when a start or stop condition occurs at an illegal position in the format frame. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. w hen a bus error occurs, t w i n t is set. to recover from a bus error, the t w sto flag must set and t w i n t must be cleared by writing a l ogic one to it. this causes the t w i to enter the not addressed slave mode and to clear the t w sto flag (no other bits in t w cr are affected). the sda and scl lines are released, and no stop condition is transmitted. 24.7.6 combining several twi modes in some cases, several t w i modes must be combined in order to complete the desired action. consider for example reading data from a serial eeprom. typically, such a transfer involves the following steps: 1. the transfer must be initiated. 2. the eeprom must be instructed what location should be read. 3. the reading must be performed. 4. the transfer must be finished. s sla r a data a $a8 $b8 a $b0 reception of the own slave address and one or more data bytes last data byte transmitted. switched to not addressed slave (twea = '0') arbitration lost as master and addressed as slave n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data $c0 data a a $c8 p or s all 1's a table 24-6. miscellaneous states status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hard- ware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xf8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer 0x00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condi- tion is sent on the bus. in all cases, the bus is released and twsto is cleared.
265 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote that data is transmitted both from master to slave and vice versa. the master must instruct the slave what location it wants to read, r equiring the use of the mt mode. subsequently, data must be read from the slave, implying the use of the mr mode. thus, the transfer direction must be changed. the master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation. if th is principle is violated in a multimaster sys- tem, another master can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data lo cation. such a change in transfe r direction is accomplished by transmitting a repeated start between the trans mission of the address byte and reception of the data. after a repeated start, the master keeps ownership of the bus. the following figure shows the flow in this transfer. figure 24-19. combining several t w i modes to access a serial eeprom 24.8 multi-master syst ems and arbitration if multiple masters are connected to the same bus, transmissions may be initiated simultane- ously by one or more of them. the t w i standard ensures that such situations are handled in such a way that one of the mast ers will be allowed to proceed wit h the transfer, and that no data will be lost in the process. an example of an ar bitration situation is depicted below, where two masters are trying to transmit data to a slave receiver. figure 24-20. an arbitration example several different scenarios may arise during arbitration, as described below: ? two or more masters are performing identical communication with the same slave. in this case, neither the slave nor any of the ma sters will know about the bus contention. ? two or more masters are accessing the same slave with different data or direction bit. in this case, arbitration will occur, either in the read/ w rite bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. losing masters will switch to no t addressed slave mode or wa it until the bus is free and transmit a new start condition, depending on application software action. master transmitter master receiver s = start rs = repeated start p = stop transmitted from master to slave transmitted from slave to master s sla+w a address a rs sla+r a data a p device 1 master transmitter device 2 master transmitter device 3 slave receiver device n sda scl ........ r1 r2 v cc
266 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? two or more masters are accessing different slav es. in this case, arbitration will occur in the sla bits. masters trying to ou tput a one on sda while anot her master outputs a zero will lose the arbitration. masters lo sing arbitration in sla will switch to slave mode to check if they are being addressed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/ w rite bit. if they are not being addressed, they will switch to not addressed slav e mode or wait until the bu s is free and transmit a new start condition, depending on application software action. this is summarized in figure 24-21 . possible status values are given in circles. figure 24-21. possible status codes caused by arbitration 24.9 register description 24.9.1 twbr ? twi bit rate register ? bits 7:0 ? twi bit rate register t w br selects the division factor for the bit rate generator. the bit rate generator is a frequency divider which generates the scl clock frequency in the master modes. see ?bit rate generator unit? on page 247 for calculating bit rates. 24.9.2 twcr ? twi control register the t w cr is used to control the operation of the t w i. it is used to enable the t w i, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the t w dr. it also indicates a write collisio n if data is at tempted written to t w dr while the register is inaccessible. own address / general call received arbitration lost in sla twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free no arbitration lost in data direction ye s write data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received read b0 68/78 38 sla start data stop bit 76543210 (0xb8) twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xbc) twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value 0 0 0 0 0 0 0 0
267 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the t w i has finished its current job and expects application software response. if the i-bit in sreg and t w ie in t w cr are set, the mcu will jump to the t w i interrupt vector. w hile the t w i n t flag is set, the scl low period is stretched. the t w i n t flag must be cleared by software by writing a logic one to it. n ote that this flag is not automati- cally cleared by hardware when executing the interr upt routine. also note that clearing this flag starts the operation of the t w i, so all accesses to the t w i address register (t w ar), t w i sta- tus register (t w sr), and t w i data register (t w dr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the t w ea bit controls the generation of the acknowledge pulse. if the t w ea bit is written to one, the ack pulse is generated on the t w i bus if the following conditions are met: 1. the device?s own slave address has been received. 2. a general call has been received, while the t w gce bit in the t w ar is set. 3. a data byte has been received in master receiver or slave receiver mode. by writing the t w ea bit to zero, the device can be virtually disconnected from the 2-wire serial bus temporarily. address recognition can then be resumed by writing the t w ea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the t w sta bit to one when it desires to become a master on the 2-wire serial bus. the t w i hardware checks if the bus is available, and generates a start condition on the bus if it is free. however, if the bus is not free, the t w i waits until a stop condition is detected, and then generates a new start condition to claim the bus master status. t w sta must be cleared by software when the start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit w riting the t w sto bit to one in master mode will g enerate a stop cond ition on the 2-wire serial bus. w hen the stop condition is executed on the bus, the t w sto bit is cleared auto- matically. in slave mode, setting the t w sto bit can be used to recover from an error condition. this will not generate a stop condition, but the t w i returns to a well-defined unaddressed slave mode and releases the scl and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the t ww c bit is set when attempting to write to the t w i data register ? t w dr when t w i n t is low. this flag is cl eared by writing the t w dr register when t w i n t is high. ? bit 2 ? twen: twi enable bit the t w e n bit enables t w i operation and activates the t w i interface. w hen t w e n is written to one, the t w i takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filters. if this bit is written to zero, the t w i is switched off and all t w i transmissions are terminated, regardless of any ongoing operation. ? bit 1 ? res: reserved bit this bit is a reserved bit an d will always read as zero.
268 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? twie: twi interrupt enable w hen this bit is written to one, and the i-bit in sreg is set, the t w i interrupt request will be acti- vated for as long as the t w i n t flag is high. 24.9.3 twsr ? twi status register ? bits 7:3 ? tws: twi status these five bits reflect the status of the t w i logic and the 2-wire serial bus. the different status codes are described late r in this section. n ote that the value read from t w sr contains both the 5-bit status value and the 2-bit prescaler value. the application designer should mask the pres- caler bits to zero when checking the status bits. this makes status checking independent of prescaler setting. this approach is used in this datasheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1:0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. to calculate bit rates, see ?bit rate generator unit? on page 247 . the value of t w ps1:0 is used in the equation. 24.9.4 twdr ? twi data register in transmit mode, t w dr contains the next byte to be transmitted. in receive mode, the t w dr contains the last byte receiv ed. it is writable while the t w i is not in the process of shifting a byte. this occurs when the t w i interrupt flag (t w i n t) is set by hardware. n ote that the data regis- ter cannot be initialized by the user before the first interrupt occurs. the data in t w dr remains stable as long as t w i n t is set. w hile data is shifted out, data on the bus is simultaneously shifted in. t w dr always contains the last byte present on the bus, except after a wake up from a sleep mode by the t w i interrupt. in this case, the contents of t w dr is undefined. in the case of a lost bus arbitration, no data is lost in the transition from master to slave. handling of the ack bit is controlled automatically by the t w i logic, the cpu cannot access the ack bit directly. bit 76543210 (0xb9) tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/write rrrrrrr/wr/w initial value 1 1 1 1 1 0 0 0 table 24-7. t w i bit rate prescaler twps1 twps0 prescaler value 001 014 1016 1164 bit 76543210 (0xbb) twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 1
269 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bits 7:0 ? twd: twi data register these eight bits constitute the next data byte to be transmitted, or the latest data byte received on the 2-wire serial bus. 24.9.5 twar ? twi (slave) address register the t w ar should be loaded with the 7-bit slave address (in the seven most significant bits of t w ar) to which the t w i will respond when programmed as a slave transmitter or receiver, and not needed in the master modes. in multimaster systems, t w ar must be set in masters which can be addressed as slaves by other masters. the lsb of t w ar is used to enable recognition of the general call address (0x00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a match is found, an interrupt request is generated. ? bits 7:1 ? twa: twi (slave) address register these seven bits constitute the slave address of the t w i unit. ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the 2-wire serial bus. 24.9.6 twamr ? twi (slave) address mask register ? bits 7:1 ? twam: twi address mask the t w amr can be loaded with a 7-bit slave a ddress mask. each of the bits in t w amr can mask (disable) the corresponding address bit in the t w i address register (t w ar). if the mask bit is set to one then the address match l ogic ignores the compare between the incoming address bit and the corresponding bit in t w ar. figure 24-22 shows the address match logic in detail. figure 24-22. t w i address match logic, block diagram bit 76543210 (0xba) twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 0 bit 76543210 (0xbd) twam[6:0] ? twamr read/write r/w r/w r/w r/w r/w r/w r/w r initial value 0 0 0 0 0 0 0 0 address match address bit comparator 0 address bit comparator 6..1 twar0 twamr0 address bit 0
270 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? res: reserved bit this bit is reserved and will always read as zero.
271 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 25. ac ? analog comparator the analog comparator compares the input values on the positive pin ai n 0 and negative pin ai n 1. w hen the voltage on the positive pin ai n 0 is higher than the voltage on the negative pin ai n 1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. th e user can select interrupt triggering on com- parator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 25-1 . the power reduction adc bit, pradc, in ?prr0 ? power reduction register 0? on page 56 must be disabled by writing a logical zero to be able to use the adc input mux. figure 25-1. analog comparator block diagram (2) n ote: 1. see table 25-1 . 2. refer to figure 1-1 on page 2 and table 13-5 on page 79 for analog comparator pin placement. 25.1 analog comparator multiplexed input it is possible to select any of the adc15:0 pins to replace the negative input to the analog com- parator. the adc multiplexer is used to select this input, and consequently, the adc must be switched off to utilize this feature. if the analog comparator multiplexer enable bit (acme in adcsrb) is set and the adc is switched off (ade n in adcsra is zero), mux5 and mux2:0 in admux select the input pin to replace the negati ve input to the analog comparator, as shown in table 25-1 . if acme is cleared or ade n is set, ai n 1 is applied to the negative input to the ana- log comparator. acbg bandgap reference adc multiplexer output acme aden (1) table 25-1. analog comparator mulitiplexed input acme aden mux5 mux2:0 analog comparator negative input 0 x x xxx ai n 1 1 1 x xxx ai n 1 1 0 0 000 adc0 1 0 0 001 adc1 1 0 0 010 adc2 1 0 0 011 adc3
272 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 25.2 register description 25.2.1 adcsrb ? adc control and status register b ? bit 6 ? acme: analog comparator multiplexer enable w hen this bit is written logic one and the adc is switched off (ade n in adcsra is zero), the adc multiplexer selects the negative input to the analog comparator. w hen this bit is written logic zero, ai n 1 is applied to the negative input of the analog comparator. for a detailed description of this bit, see ?analog comparator multiplexed input? on page 271 . 25.2.2 acsr ? analog comparator control and status register ? bit 7 ? acd: analog comparator disable w hen this bit is written logic one , the power to the analog comparator is switched off. this bit can be set at any time to tu rn off the analog com parator. this will reduce power consumption in active and idle mode. w hen changing the acd bit, the analog comparator interrupt must be disabled by clearing the acie bit in acsr. otherwise an interrupt can occur when the bit is changed. 1 0 0 100 adc4 1 0 0 101 adc5 1 0 0 110 adc6 1 0 0 111 adc7 1 0 1 000 adc8 1 0 1 001 adc9 1 0 1 010 adc10 1 0 1 011 adc11 1 0 1 100 adc12 1 0 1 101 adc13 1 0 1 110 adc14 1 0 1 111 adc15 table 25-1. analog comparator mulitiplexed input (continued) acme aden mux5 mux2:0 analog comparator negative input bit 7 6543210 (0x7b) ? acme ? ? mux5 adts2 adts1 adts0 adcsrb read/ w rite r r/ w rrr/ w r/ w r/ w r/ w initial value0 0000000 bit 76543210 0x30 (0x50) acd acbg aco aci acie acic acis1 acis0 acsr read/ w rite r/ w r/ w rr/ w r/ w r/ w r/ w r/ w initial value 0 0 n /a00000
273 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 ? acbg: analog comparator bandgap select w hen this bit is set, a fixed bandgap reference volt age replaces the positive input to the analog comparator. w hen this bit is cleared, ai n 0 is applied to the positive input of the analog compar- ator. w hen the bandgap reference is used as input to the analog comparator, it will take a certain time for the voltage to stabilize. if not stabilized, the first conversion may give a wrong value. see ?internal voltage reference? on page 62. ? bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interr upt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when executing the corresponding inter- rupt handling vector. alternatively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable w hen the acie bit is written logic one and the i-bit in the status register is set, the analog com- parator interrupt is activated. w hen written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable w hen written logic one, this bit enables the input capture function in timer/counter1 to be trig- gered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the compar ator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. w hen written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator trigger the timer/counter1 input capture interrupt, the icie1 bit in the timer interrupt mask register (timsk1) must be set. ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator interrupt. the different settings are shown in table 25-2 . w hen changing the acis1/acis0 bits, the analog comparator interrupt must be disabled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. table 25-2. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle 01reserved 1 0 comparator interrupt on falling output edge 1 1 comparator interrupt on rising output edge
274 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 25.2.3 didr1 ? digital in put disable register 1 ? bit 1, 0 ? ain1d, ain0d: ai n1, ain0 digita l input disable w hen this bit is written logic one, the digital input buffer on the ai n 1/0 pin is disabled. the corre- sponding pi n register bit will always read as zero when th is bit is set. w hen an analog signal is applied to the ai n 1/0 pin and the digital input from this pin is not needed, this bit should be writ- ten logic one to reduce power consumption in the digital input buffer. bit 76543210 (0x7f) ? ? ? ? ? ? ain1d ain0d didr1 read/ w riterrrrrrr/ w r/ w initial value00000000
275 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26. adc ? analog to digital converter 26.1 features ? 10-bit resolution ? 1 lsb integral non-linearity ? 2 lsb absolute accuracy ? 13s - 260s conversion time ? up to 76.9ksps (up to 15ksp s at maximum resolution) ? 16 multiplexed single ended input channels ? 14 differential input channels ? 4 differential input ch annels with optional gain of 10 and 200 ? optional left adjustment for adc result readout ? 0v - v cc adc input voltage range ? 2.7v - v cc differential adc voltage range ? selectable 2.56v or 1.1v adc reference voltage ? free running or single conversion mode ? interrupt on adc conversion complete ? sleep mode no ise canceler the atmega640/1280/1281/2560/2561 features a 10-bit successive approximation adc. the adc is connected to an 8/16-channel analog mult iplexer which allows eight/sixteen single- ended voltage inputs constructed from the pins of port f and port k. the single-ended voltage inputs refer to 0v (g n d). the device also supports 16/32 differential voltage input combinations. four of the differential inputs (adc1 & adc0, adc3 & adc2, adc9 & adc8 and adc11 & adc10) are equipped with a programmable gain stage, providing amplificati on steps of 0 db (1), 20 db (10) or 46 db (200) on the differential input voltage before the adc conversion. the 16 channels are split in two sections of 8 channels where in each section seven differential analog input channels share a common negative terminal (a dc1/adc9), while any other adc input in that section can be selected as the positive input terminal. if 1 or 10 gain is used, 8 bit resolution can be expected. if 200 gain is used, 7 bit resolution can be expected. the adc contains a sample and hold circuit whic h ensures that the input voltage to the adc is held at a constant level during conversion. a block diagram of the adc is shown in figure 26-1 on page 276 . the adc has a separate analog supply voltage pi n, avcc. avcc must not differ more than 0.3v from v cc . see the paragraph ?adc n oise canceler? on page 283 on how to connect this pin. internal reference voltages of nominally 1.1v, 2.56v or avcc are provided on-chip. the voltage reference may be externally decoupled at the aref pin by a capacitor for better noise performance. the power reduction adc bit, pradc, in ?prr0 ? power reduction register 0? on page 56 must be disabled by writing a logical zero to enable the adc.
276 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 26-1. analog to digital converter block schematic 26.2 operation the adc converts an analog input voltage to a 10-bit digital value through successive approxi- mation. the minimum value represents g n d and the maximum value represents the voltage on the aref pin minus 1 lsb. optionally, avcc or an internal 1.1v or 2.56v reference voltage may be connected to the aref pin by writing to the refsn bits in the admux register. the internal voltage reference may thus be decoupled by an external capacitor at the aref pin to improve noise immunity. the analog input channel is selected by writing to the mux bits in admux and adcsrb. any of the adc input pins, as well as g n d and a fixed bandgap voltage reference, can be selected as single ended inputs to the adc. a selection of adc input pins can be selected as positive and negative inputs to the differential amplifier. adc conversion complete irq 8-bit databus 15 0 adie adfr adsc aden adif adif mux[4:0] adps[2:0] sample & hold comparator internal reference (1.1v/2.56v) avcc refs[1:0] adlar channel selection adc[9:0] adc multiplexer output gain amplifie r aref bandgap (1.1v) reference gnd conversion logic adc ctrl & status register b (adcsrb) adc ctrl & status register a (adcsra) prescaler adc multiplexer select (admux) mux decoder diff / gain select adc data register (adch/adcl) adc[2:0] trigger select start interrupt flags adts[2:0] + - adc[15:0] + - 10-bit dac mux[5] adc[10:8]
277 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 if differential channels are selected, the voltage difference between the selected input channel pair then becomes the analog input to the adc. if single ended channels are used, the amplifier is bypassed altogether. the adc is enabled by setting the adc enable bit, ade n in adcsra. voltage reference and input channel selections will no t go into effect until ade n is set. the adc does not consume power when ade n is cleared, so it is recommended to switch off the adc before entering power saving sleep modes. the adc generates a 10-bit result which is pr esented in the adc data registers, adch and adcl. by default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the adlar bit in admux. if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch, to ensure that the content of the data registers belongs to the same conversion. once adcl is read, adc access to data registers is blocked. this means that if adcl has been read, and a conversion completes before adch is read, neither register is updated and the result from the conversion is lost. w hen adch is read, adc access to the adch and ad cl registers is re-enabled. the adc has its own interrupt which can be triggered when a conversion completes. w hen adc access to the data registers is prohibited between reading of adch and adcl, the interrupt will trigger even if the result is lost. 26.3 starting a conversion a single conversion is started by writing a l ogical one to the adc start conversion bit, adsc. this bit stays high as long as the conversi on is in progress and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversion is in progress, the adc will finish the current conv ersion before performing the channel change. alternatively, a conversion can be triggered automatically by various sources. auto triggering is enabled by setting the adc auto trigger enable bi t, adate in adcsra. the trigger source is selected by setting the adc trigger select bits, adts in adcsrb (see description of the adts bits for a list of the trigger sources). w hen a positive edge occurs on the selected trigger signal, the adc prescaler is reset and a conversion is st arted. this provides a method of starting con- versions at fixed intervals. if the trigger signal still is set when the conversion completes, a new conversion will not be star ted. if another positive edge occurs on the trigger si gnal during con- version, the edge will be ignored. n ote that an interrupt flag will be set even if the specific interrupt is disabled or the global interrupt enable bit in sreg is cleared. a conversion can thus be triggered without causing an interrupt. however, the interrupt flag must be cleared in order to trigger a new conversion at the next interrupt event.
278 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 26-2. adc auto trigger logic using the adc interrupt flag as a trigger source makes the adc start a new conversion as soon as the ongoing conversion has finished. the adc then operates in free running mode, con- stantly sampling and updating the adc data register. the first conversion must be started by writing a logical one to the adsc bit in adcs ra. in this mode the adc will perform successive conversions independently of whether the a dc interrupt flag, adif is cleared or not. if auto triggering is enabled, single conversi ons can be started by writing adsc in adcsra to one. adsc can also be used to determine if a conversion is in progress. the adsc bit will be read as one during a conversion, independently of how the conversion was started. 26.4 prescaling and conversion timing figure 26-3. adc prescaler by default, the successive approximation circ uitry requires an input clock frequency between 50khz and 200khz. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be as high as 1000khz to get a higher sample rate. the adc module contains a prescaler, which generates an acceptable adc clock frequency from any cpu frequency above 100khz. the prescaling is set by the adps bits in adcsra. ad s c adif s ource 1 s ource n adt s [2:0] conver s ion logic pre s caler s ta rt clk adc . . . . edge detector adate 7-bit adc pre s caler adc clock s ource ck adp s 0 adp s 1 adp s 2 ck/12 8 ck/2 ck/4 ck/ 8 ck/16 ck/32 ck/64 reset aden s tart
279 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the prescaler starts counting from the moment the adc is switched on by setting the ade n bit in adcsra. the prescaler keeps running for as long as the ade n bit is set, and is continuously reset when ade n is low. w hen initiating a single ended conversion by setti ng the adsc bit in adcsra, the conversion starts at the following rising edge of the adc clock cycle. a normal conversion takes 13 adc clock cycles. the first conversion after the adc is switched on (ade n in adcsra is set) takes 25 adc clock cycle s in order to initialize the analog circuitry. w hen the bandgap reference voltage is used as input to the adc, it will take a certain time for the voltage to stabilize. if not stabilized, the first value read after the first conversion may be wrong. the actual sample-and-hold takes place 1.5 adc clock cycles after the start of a normal conver- sion and 13.5 adc clock cycles afte r the start of an first conversion. w hen a conversion is complete, the result is written to the adc data re gisters, and adif is set. in single conversion mode, adsc is cleared simultaneously. the software may then set adsc again, and a new conversion will be init iated on the first rising adc clock edge. w hen auto triggering is used, the prescaler is reset when the trigger event occurs. this assures a fixed delay from the trigger event to the start of conversion. in this mode, the sample-and-hold takes place two adc clock cycles after the rising edge on the trigger source signal. three addi- tional cpu clock cycles are used for synchronization logic. in free running mode, a new conversion will be started immediately after the conversion com- pletes, while adsc remains high. for a summary of conversion times, see table 26-1 on page 281 . figure 26-4. adc timing diagram, first conver sion (single conversion mode) s ign and m s b of result l s b of result adc clock ad s c s ample & hold adif adch adcl cycle number aden 1 212 13 14 15 16 17 1 8 19 20 21 22 23 24 25 1 2 first conversion next conversion 3 mux and ref s update mux and ref s update conversion complete
280 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 26-5. adc timing diagram, single conversion figure 26-6. adc timing diagram, auto triggered conversion figure 26-7. adc timing diagram, free running conversion 1 2 3 4 5 6 7 8 9 10 11 12 13 s ign and m s b of result l s b of result adc clock ad s c adif adch adcl cycle number 12 one conversion next conversion 3 s ample & hold mux and ref s update conversion complete mux and ref s update 1 2 3 4 5 6 7 8 9 10 11 12 13 s ign and m s b of result l s b of result adc clock trigger s ource adif adch adcl cycle number 12 one conversion next conversion conversion complete prescaler reset adate prescaler reset s ample & hold mux and ref s update 11 12 13 s ign and m s b of result l s b of result adc clock ad s c adif adch adcl cycle number 12 one conversion next conversion 34 conversion complete s ample & hold mux and ref s update
281 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.4.1 differential channels w hen using differential channels, certain aspe cts of the conversion need to be taken into consideration. differential conversions are synchronized to the internal clock ck adc2 equal to half the adc clock. this synchronization is done automatically by the adc interface in such a way that the sample-and-hold occurs at a specific phase of ck adc2 . a conversion initiated by the user (that is, all single conversions, and the first free running conversion) when ck adc2 is low will take the same amount of time as a single ended conversion (13 adc clock cycles from the next pres- caled clock cycle). a conversion initiated by the user when ck adc2 is high will take 14 adc clock cycles due to the synchronization mechanism. in free running mode, a new conversion is initi- ated immediately after the previous conversion completes, and since ck adc2 is high at this time, all automatically started (that is, all but the first) free running conversions will take 14 adc clock cycles. if differential channels are used and conversions ar e started by auto triggering, the adc must be switched off between conversions. w hen auto triggering is used, the adc prescaler is reset before the conversion is started. since the stage is dependent of a stable adc clock prior to the conversion, this conversion w ill not be valid. by disabling a nd then re-enabling the adc between each conversion (writing ade n in adcsra to ?0? then to ?1 ?), only extended conversions are performed. the result from the extended conversions will be valid. see ?prescaling and conver- sion timing? on page 278 for timing details. table 26-1. adc conversion time condition sample & hold (cycles from start of conversion) conversion time (cycles) first conversion 13.5 25 n ormal conversions, single ended 1.5 13 auto triggered conversions 2 13.5 n ormal conversions, differential 1.5/2.5 13/14
282 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.5 changing channel or reference selection the muxn and refs1:0 bits in the admux register are single buffered through a temporary register to which the cpu has random access. this ensures that the channels and reference selection only takes place at a safe point dur ing the conversion. the channel and reference selection is continuously updated until a conversion is started. once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the adc. con- tinuous updating resumes in the last adc clock cycle before the conversion completes (adif in adcsra is set). n ote that the conversion starts on the following rising adc clock edge after adsc is written. the user is thus advised not to write new channel or reference selection values to admux until one adc clock cycle after adsc is written. if auto triggering is used, the exact time of t he triggering event can be indeterministic. special care must be taken when updating the admux register, in order to control which conversion will be affected by the new settings. if both adate and ade n is written to one, an interrupt event can occur at any time. if the admux register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. admux can be safely updated in the following ways: 1. w hen adate or ade n is cleared. 2. during conversion, minimum one adc clock cycle after the trigger event. 3. after a conversion, before the interrupt flag used as trigger source is cleared. w hen updating admux in one of these conditions, t he new settings will affect the next adc conversion. special care should be taken when changing differential channels. once a differential channel has been selected, the stage may take as much as 125s to stabilize to the new value. thus conversions should not be started within the first 125s after selecting a new differential chan- nel. alternatively, conversion results obt ained within this period should be discarded. the same settling time should be observed for th e first differential conversion after changing adc reference (by changing the refs1:0 bits in admux). 26.5.1 adc input channels w hen changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: in single conversion mode, always select the channel before starting the conversion. the chan- nel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the conversion to complete before changing the channel selection. in free running mode, always select the channel before starting the first conversion. the chan- nel selection may be changed one adc clock cycle after writing one to adsc. however, the simplest method is to wait for the first conversion to complete, and then change the channel selection. since the next conver sion has already started automati cally, the next result will reflect the previous channel selection. subsequent conversions will refl ect the new channel selection. w hen switching to a differential gain channel, the first conversion result may have a poor accu- racy due to the required settling time for the automatic offset cancellation circuitry. the user should preferably disregard the first conversion result.
283 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.5.2 adc voltage reference the reference voltage for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in code s close to 0x3ff. v ref can be selected as either avcc, internal 1.1v reference, internal 2.56v reference or external aref pin. avcc is connected to the adc through a passive switch. the internal 1.1v reference is gener- ated from the internal bandgap reference (vbg) through an internal amplifier. in either case, the external aref pin is directly connected to the adc, and the reference voltage can be made more immune to noise by connecting a capacitor between the aref pin and ground. v ref can also be measured at the aref pin with a high impedant voltmeter. n ote that v ref is a high impedant source, and only a capacitive load shoul d be connected in a system. the internal 2.56v reference is generated from the 1.1v reference. if the user has a fixed voltage source connected to the aref pin, the user may not use the other reference voltage options in the ap plication, as they will be shorte d to the external voltage. if no external voltage is applied to the aref pin, the user may switch between avcc, 1.1v and 2.56v as reference selection. the first adc c onversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result. if differential channels are used, the selected reference should not be closer to avcc than indicated in ?adc characteristics ? preliminary data? on page 377 . 26.6 adc noise canceler the adc features a noise canceler that enables conversion during sleep mode to reduce noise induced from the cpu core and other i/o peripherals. the noise canceler can be used with adc n oise reduction and idle mode. to make use of this feature, the following procedure should be used: 1. make sure that the adc is enabled and is not busy converting. single conversion mode must be selected and the adc conversion complete interrupt must be enabled. 2. enter adc n oise reduction mode (or idle mo de). the adc will start a conversion once the cpu has been halted. 3. if no other interrupts occur before the adc conversion completes, the adc interrupt will wake up the cpu and execute the adc co nversion complete interrupt routine. if another interrupt wakes up the cpu before the adc conversion is complete, that interrupt will be executed, and an adc conv ersion complete interrupt request will be generated when the adc conversion complete s. the cpu will remain in active mode until a new sleep command is executed. n ote that the adc will not be automatically turned off when entering other sleep modes than idle mode and adc n oise reduction mode. the user is advised to write zero to ade n before enter- ing such sleep modes to avoid excessive power consumption. if the adc is enabled in such sleep modes and the user wants to perform differential conver- sions, the user is advised to switch the adc off and on after waking up from sleep to prompt an extended conversion to get a valid result.
284 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.6.1 analog input circuitry the analog input circuitry for single ended channels is illustrated in figure 26-8. an analog source applied to adcn is subjected to the pin capacitance and input leakage of that pin, regard- less of whether that channel is selected as input for the adc. w hen the channel is selected, the source must drive the s/h capacitor through the series resistance (combined resistance in the input path). the adc is optimized for analog signals with an output impedance of approximately 10k or less. if such a source is used, the sampling time will be negligible. if a source with higher imped- ance is used, the sampling time will depend on how long time the source nee ds to charge the s/h capacitor, which can vary widely. the user is recommended to only use low impedant sources with slowly varying signals, since this mi nimizes the required charge transfer to the s/h capacitor. signal components higher than the n yquist frequency (f adc /2) should not be present for either kind of channels, to avoid distortion from unpredictable signal convolution. the user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the adc. figure 26-8. analog input circuitry 26.6.2 analog noise canceling techniques digital circuitry inside and outside the device ge nerates emi which might affect the accuracy of analog measurements. if conversion accuracy is critical, the noise level can be reduced by applying the following techniques: 1. keep analog signal paths as short as possible. make sure analog tracks run over the ground plane, and keep them well away from high-speed switching digital tracks. 2. the avcc pin on the device should be connected to the digital v cc supply voltage via an lc network as shown in figure 26-9 on page 285 . 3. use the adc noise canceler function to reduce induced noise from the cpu. 4. if any adc port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. adcn i ih 1..100 k c s/h = 14 pf v cc /2 i il
285 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 26-9. adc power connections, atmega1281/2561. figure 26-10. adc power connections, atmega640/1280/2560 vcc gnd 100 n f 100nf ground plane (adc0) pf0 (adc7) pf7 (adc1) pf1 (adc2) pf2 (adc3) pf3 (adc4) pf4 (adc5) pf5 (adc6) pf6 aref gnd avcc 52 53 54 55 56 57 58 59 60 61 61 62 62 63 63 64 64 1 51 pg5 pa0 10 ? 100nf gro u nd pl a ne 100 (oc0b) pg5 10 ? 79 80 81 82 8 3 84 85 86 87 88 89 90 91 92 9 3 94 95 96 97 98 99 pj7 vcc gnd (adc15/pcint2 3 ) pk7 (adc14/pcint22) pk6 (adc1 3 /pcint21) pk5 (adc12/pcint20) pk4 (adc11/pcint19) pk 3 (adc10/pcint18) pk2 (adc9/pcint17) pk1 (adc8/pcint16) pk0 (adc7/tdi) pf7 (adc6/tdo) pf6 (adc5/tms) pf5 (adc4/tck) pf4 (adc 3 ) pf 3 (adc2) pf2 (adc1) pf1 (adc0) pf0 aref gnd avcc
286 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.6.3 offset compensation schemes the stage has a built-in offset cancellation circuitr y that nulls the offset of differential measure- ments as much as possible. the remaining offset in the analog path can be measured directly by selecting the same channel for both differential inputs. this offset residue can be then sub- tracted in software from the measurement results. using this kind of software based offset correction, offset on any channel can be reduced below one lsb. 26.6.4 adc accuracy definitions an n-bit single-ended adc converts a voltage linearly between g n d and v ref in 2 n steps (lsbs). the lowest code is read as 0, and the highest code is read as 2 n -1. several parameters describe the deviation from the ideal behavior: ? offset: the deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 lsb). ideal value: 0 lsb. figure 26-11. offset error ? gain error: after adjusting for offset, the gain error is found as the deviation of the last transition (0x3fe to 0x3ff) compared to the ideal transition (at 1.5 lsb below maximum). ideal value: 0 lsb. figure 26-12. gain error output code v ref input voltage ideal adc actual adc offset error output code v ref input voltage ideal adc actual adc gain error
287 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ?integral n on-linearity (i n l): after adjusting for offset and gain error, the i n l is the maximum deviation of an actual transition compared to an ideal transition for any code. ideal value: 0 lsb. figure 26-13. integral n on-linearity (i n l) ? differential n on-linearity (d n l): the maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. figure 26-14. differential n on-linearity (d n l) ? quantization error: due to the quantization of the input voltage into a finite number of codes, a range of input voltages (1 lsb wide) will code to the same value. always 0.5 lsb. ? absolute accuracy: the maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. this is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. ideal value: 0.5 lsb. output code v ref input voltage ideal adc actual adc inl output code 0x3ff 0x000 0 v ref input voltage dnl 1 l s b
288 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.7 adc conversion result after the conversion is complete (adif is high ), the conversion result can be found in the adc result registers (adcl, adch). for single ended conversion, the result is where v i n is the voltage on the selected input pin and v ref the selected voltage reference (see table 26-3 on page 289 and table 26-4 on page 290 ). 0x000 represents analog ground, and 0x3ff represents the selected reference voltage minus one lsb. if differential channels are used, the result is where v pos is the voltage on the positive input pin, v n eg the voltage on the negative input pin, and v ref the selected voltage reference. the result is presented in two?s complement form, from 0x200 (-512d) through 0x1ff (+511d). n ote that if the user wants to perform a quick polarity check of the result, it is sufficient to read the msb of the result (adc9 in adch). if the bit is one, the result is negative, and if this bit is zero, the result is positive. figure 26-15 shows the decod- ing of the differential input range. table 26-2 on page 289 shows the resulting output codes if the differential input channel pair (adcn - adcm) is selected with a gain of gai n and a reference voltage of v ref . figure 26-15. differential measurement range adc v in 1024 ? v ref -------------------------- = adc v pos v neg ? () 512 ? v ref ---------------------------------------------------- - = 0 output code 0x1ff 0x000 v ref differential input voltage (volts) 0x3ff 0x200 - v ref
289 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 example: admux = 0xfb (adc3 - adc2, 10 gain, 2.56v reference, left adjusted result). voltage on adc3 is 300mv, voltage on adc2 is 500mv. adcr = 512 10 (300 - 500) / 2560 = -400 = 0x270. adcl will thus read 0x00, and adch will read 0x9c. w riting zero to adlar right adjusts the result: adcl = 0x70, adch = 0x02. 26.8 register description 26.8.1 admux ? adc multiplexer selection register ? bit 7:6 ? refs1:0: reference selection bits these bits select the voltage reference for the adc, as shown in table 26-3 . if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). the internal voltage reference options may not be used if an external reference voltage is being applied to the aref pin. n ote: 1. if 10x or 200x gain is selected, only 2.56v should be used as internal voltage reference. for differential conversion, only 1.1v cannot be used as internal voltage reference. table 26-2. correlation between input voltage and output codes v adcn read code corresponding decimal value v adcm + v ref / gai n 0x1ff 511 v adcm + 0.999 v ref / gai n 0x1ff 511 v adcm + 0.998 v ref / gai n 0x1fe 510 ... ... ... v adcm + 0.001 v ref / gai n 0x001 1 v adcm 0x000 0 v adcm - 0.001 v ref / gai n 0x3ff -1 ... ... ... v adcm - 0.999 v ref / gai n 0x201 -511 v adcm - v ref / gai n 0x200 -512 bit 76543210 (0x7c) refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 admux read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0 table 26-3. voltage reference selections for adc refs1 refs0 voltage reference selection (1) 0 0 aref, internal v ref turned off 0 1 avcc with external capacitor at aref pin 1 0 internal 1.1v voltage reference with external capacitor at aref pin 1 1 internal 2.56v voltage reference with external capacitor at aref pin
290 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data register. w rite one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adlar bit will affect t he adc data register immediately, regardless of any ongoing conver- sions. for a complete description of this bit, see ?adcl and adch ? the adc data register? on page 294 . ? bits 4:0 ? mux4:0: analog channel and gain selection bits the value of these bits selects which combination of analog inputs are connected to the adc. see table 26-4 for details. if these bits are changed during a conversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). 26.8.2 adcsrb ? adc control and status register b ? bit 3 ? mux5: analog channel and gain selection bit this bit is used together with mux4:0 in admu x to select which combin ation in of analog inputs are connected to the adc. see table 26-4 for details. if this bit is changed during a conversion, the change will not go in effect until this co nversion is complete. this bit is not valid for atmega1281/2561. bit 76543210 (0x7b) ? acme ? ?mux5 adts2 adts1 adts0 adcsrb read/ w rite r r/ w rrr/ w r/ w r/ w r/ w initial value 00000000 table 26-4. input channel selections mux5:0 single ended input positive differential input negative differential input gain 000000 adc0 n /a 000001 adc1 000010 adc2 000011 adc3 000100 adc4 000101 adc5 000110 adc6 000111 adc7
291 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 001000 (1) n /a adc0 adc0 10 001001 (1) adc1 adc0 10 001010 (1) adc0 adc0 200 001011 (1) adc1 adc0 200 001100 (1) adc2 adc2 10 001101 (1) adc3 adc2 10 001110 (1) adc2 adc2 200 001111 (1) adc3 adc2 200 010000 adc0 adc1 1 010001 adc1 adc1 1 010010 adc2 adc1 1 010011 adc3 adc1 1 010100 adc4 adc1 1 010101 adc5 adc1 1 010110 adc6 adc1 1 010111 adc7 adc1 1 011000 adc0 adc2 1 011001 adc1 adc2 1 011010 n /a adc2 adc2 1 011011 adc3 adc2 1 011100 adc4 adc2 1 011101 adc5 adc2 1 011110 1.1v (v bg ) n /a 011111 0v (g n d) 100000 adc8 n /a 100001 adc9 100010 adc10 100011 adc11 100100 adc12 100101 adc13 100110 adc14 100111 adc15 table 26-4. input channel selections (continued) mux5:0 single ended input positive differential input negative differential input gain
292 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. to reach the given accuracy, 10 or 200 gain should not be used for operating voltage below 2.7v. 26.8.3 adcsra ? adc control and status register a ? bit 7 ? aden: adc enable w riting this bit to one enables the adc. by writing it to zero, the adc is turned off. turning the adc off while a conversion is in prog ress, will terminate this conversion. 101000 (1) n /a adc8 adc8 10 101001 (1) adc9 adc8 10 101010 (1) adc8 adc8 200 101011 (1) adc9 adc8 200 101100 (1) adc10 adc10 10 101101 (1) adc11 adc10 10 101110 (1) adc10 adc10 200 101111 (1) adc11 adc10 200 110000 adc8 adc9 1 110001 adc9 adc9 1 110010 adc10 adc9 1 110011 adc11 adc9 1 110100 adc12 adc9 1 110101 adc13 adc9 1 110110 adc14 adc9 1 110111 adc15 adc9 1 111000 adc8 adc10 1 111001 adc9 adc10 1 111010 adc10 adc10 1 111011 adc11 adc10 1 111100 adc12 adc10 1 111101 n /a adc13 adc10 1 111110 reserved n /a 111111 reserved n /a table 26-4. input channel selections (continued) mux5:0 single ended input positive differential input negative differential input gain bit 76543210 (0x7a) aden adsc adate adif adie adps2 adps1 adps0 adcsra read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000
293 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 ? adsc: adc start conversion in single conversion mode, write this bit to one to start each conversion. in free running mode, write this bit to one to start the first conversion. the first conversion after adsc has been written after the adc has been enabled, or if adsc is written at the same time as the adc is enabled, will take 25 adc clock cycles instead of the norma l 13. this first conversi on performs initializa- tion of the adc. adsc will read as one as long as a conversion is in progress. w hen the conversion is complete, it returns to zero. w riting zero to this bit has no effect. ? bit 5 ? adate: adc auto trigger enable w hen this bit is written to one, auto triggering of the adc is enabled. the adc will start a con- version on a positive edge of the selected trigger signal. the trigger source is selected by setting the adc trigger select bits, adts in adcsrb. ? bit 4 ? adif: adc interrupt flag this bit is set when an adc conversion completes and the data registers are updated. the adc conversion complete interrupt is executed if the adie bit and the i-bit in sreg are set. adif is cleared by hardware when executing th e corresponding interrupt handling vector. alter- natively, adif is cleared by writing a logical one to the flag. beware that if doing a read-modify- w rite on adcsra, a pending interrupt can be dis abled. this also applies if the sbi and cbi instructions are used. ? bit 3 ? adie: adc interrupt enable w hen this bit is written to one and the i-bit in sreg is set, the adc conversion complete inter- rupt is activated. ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the xtal frequency and the input clock to the adc. table 26-5. adc prescaler selections adps2 adps1 adps0 division factor 0002 0012 0104 0118 10016 10132 11064 111128
294 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 26.8.4 adcl and adch ? the adc data register 26.8.4.1 adlar = 0 26.8.4.2 adlar = 1 w hen an adc conversion is complete, the result is found in these two registers. if differential channels are used, the result is presented in two?s complement form. w hen adcl is read, the adc data register is not updated until adch is read. consequently, if the result is left adjusted and no more than 8-bit precision (7 bit + sign bit for differential input channels) is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch. the adlar bit in admux, and the muxn bits in admux affect the way the result is read from the registers. if adlar is set, the result is left adjusted. if adla r is cleared (default), the result is right adjusted. ? adc9:0: adc conversion result these bits represent the result from the conversion, as detailed in ?adc conversion result? on page 288 . 26.8.5 adcsrb ? adc control and status register b ? bit 7 ? res: reserved bit this bit is reserved for future use. to ensure co mpatibility with future de vices, this bit must be written to zero when adcsrb is written. ? bit 2:0 ? adts2:0: adc auto trigger source if adate in adcsra is written to one, the value of these bits selects which source will trigger an adc conversion. if adate is cleared, the adts2:0 settings will have no effect. a conversion will be triggered by the rising edge of the se lected interr upt flag. n ote that switching from a trig- bit 151413121110 9 8 (0x79) ? ? ? ? ? ? adc9 adc8 adch (0x78) adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl 76543210 read/ w rite rrrrrrrr rrrrrrrr initial value00000000 00000000 bit 151413121110 9 8 (0x79) adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch (0x78) adc1 adc0 ? ????? adcl 76543210 read/ w rite rrrrrrrr rrrrrrrr initial value00000000 00000000 bit 76543210 (0x7b) ? acme ? ? mux5 adts2 adts1 adts0 adcsrb read/ w rite r r/ w rrr/ w r/ w r/ w r/ w initial value 00000000
295 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. if ade n in adcsra is set, this will start a conversion. switchin g to free running mode (adts[2:0]=0) will not cause a trigger event, even if t he adc interrupt flag is set . n ote: free running mode cannot be used for differential channels (see chapter ?differential channels? on page 281 ). 26.8.6 didr0 ? digital in put disable register 0 ? bit 7:0 ? adc7d:adc0d: ad c7:0 digital input disable w hen this bit is written logic one, the digital input buffer on the corresponding adc pin is dis- abled. the corresponding pi n register bit will always read as zero when this bit is set. w hen an analog signal is applied to the adc7:0 pin and the di gital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 26.8.7 didr2 ? digital in put disable register 2 ? bit 7:0 ? adc15d:adc8d: adc15:8 digital input disable w hen this bit is written logic one, the digital input buffer on the corresponding adc pin is dis- abled. the corresponding pi n register bit will always read as zero when this bit is set. w hen an analog signal is applied to the adc15:8 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. table 26-6. adc auto trigger source selections adts2 adts1 adts0 trigger source 0 0 0 free running mode 0 0 1 analog comparator 0 1 0 external interrupt request 0 0 1 1 timer/counter0 compare match a 1 0 0 timer/counter0 overflow 1 0 1 timer/counter1 compare match b 1 1 0 timer/counter1 overflow 1 1 1 timer/counter1 capture event bit 76543210 (0x7e) adc7d adc6d adc5d adc4d adc3d adc2d adc1d adc0d didr0 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value00000000 bit 76543210 (0x7d) adc15d adc14d adc13d adc12d adc11d adc10d adc9d adc8d didr2 read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
296 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 27. jtag interface and on-chip debug system 27.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan ca pabilities according to the i eee std. 1149.1 (jtag) standard ? debugger access to: ? all internal peripheral units ? internal and external ram ? the internal register file ?program counter ? eeprom and flash memories ? extensive on-chip debug support for break conditions, including ? avr break instruction ? break on change of program memory flow ? single step break ? program memory break points on single address or address range ? data memory break points on si ngle address or address range ? programming of flash, eeprom , fuses, and lock bits th rough the jtag interface ? on-chip debugging supported by avr studio ? 27.2 overview the avr ieee std. 1149.1 compliant jtag interface can be used for ? testing pcbs by using the jtag boundary-scan capability ? programming the non-volatile memories, fuses and lock bits ? on-chip debugging a brief description is given in the following se ctions. detailed descriptions for programming via the jtag interface, and using the boundary-scan chain can be found in the sections ?program- ming via the jtag interface? on page 354 and ?ieee 1149.1 (jtag) bo undary-scan? on page 302 , respectively. the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third party vendors only. figure 27-1 on page 297 shows a block diagram of the jtag interface and the on-chip debug system. the tap controller is a state machine controlled by the tck and tms signals. the tap controller selects either the jtag instruction register or one of several data registers as the scan chain (shift register) between the tdi ? input and tdo ? output. the instruction register holds jtag instructions controlling the behavior of a data register. the id-register, bypass register, and the bou ndary-scan chain are the data registers used for board-level testing. the jtag programming interface (actually consisting of several physical and virtual data registers) is used for serial programming via the jtag interface. the internal scan chain and break point scan chain are used for on-chip debugging only.
297 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 27-1. block diagram 27.3 tap - test access port the jtag interface is accessed through four of the avr?s pins. in jtag terminology, these pins constitute the test access port ? tap. these pins are: ? tms : test mode select. this pin is used for navigating through the tap-controller state machine. ? tck : test clock. jtag operation is synchronous to tck. ? tdi : test data in. serial input data to be shifted in to the instruction register or data register (scan chains). ? tdo : test data out. serial output data from instruction register or data register. the ieee std. 1149.1 also specifies an optional tap signal; trst ? test reset ? which is not provided. w hen the jtage n fuse is unprogrammed, these four tap pins are normal port pins, and the tap controller is in reset. w hen programmed, the input tap signals are internally pulled high and the jtag is enabled for boundary-scan and programming. the device is shipped with this fuse programmed. for the on-chip debug system, in addition to the jtag interface pins, the reset pin is moni- tored by the debugger to be able to detect external reset sources. the debugger can also pull the reset pin low to reset the whole system, assuming only open collectors on the reset line are used in the application. tap controller tdi tdo tck tm s fla s h memory avr cpu digital peripheral unit s jtag / avr core communication interface breakpoint unit flow control unit ocd s tatu s and control internal s can chain m u x in s truction regi s ter id regi s ter bypa ss regi s ter jtag programming interface pc instruction address data breakpoint s can chain addre ss decoder analog peripherial unit s i/o port 0 i/o port n boundary s can chain analog inputs control & clock lines device boundary
298 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 27-2. tap controller state diagram 27.3.1 tap controller the tap controller is a 16-state finite state machine that controls the operation of the boundary- scan circuitry, jtag programming circuitry, or on-chip debug system. the state transitions depicted in figure 27-2 depend on the signal present on tm s (shown adjacent to each state transition) at the time of the rising edge at tck. the initial state after a power-on reset is test- logic-reset. as a definition in this document, the lsb is shifted in and out first for all shift registers. assuming run-test/idle is the present state, a typical scenario for using the jtag interface is: ? at the tms input, apply the sequence 1, 1, 0, 0 at the rising edges of tck to enter the shift instruction register ? shift-ir state. w hile in this state, shift the four bits of the jtag instructions into the jtag instruction register from the tdi input at the rising edge of tck. the tms input must be held low during input of the 3 lsbs in order to remain in the shift-ir state. the msb of the instruction is shifted in when this state is left by setting tms high. w hile the instruction is shifted in from the tdi pin, the captured ir-state 0x01 is shifted out on the tdo pin. the jtag instruction selects a particular data register as path between tdi and tdo and controls the circuitry surrounding the selected data register. test-logic-reset run-test/idle s hift-dr exit1-dr pause-dr exit2-dr update-dr s elect-ir s can capture-ir s hift-ir exit1-ir pause-ir exit2-ir update-ir s elect-dr s can capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
299 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. the instruction is latched onto the parallel output from the shift register path in the update-ir state. the exit- ir, pause-ir, and exit2-ir states are onl y used for navigating the state machine. ? at the tms input, apply the sequence 1, 0, 0 at the rising edges of tck to enter the shift data register ? shift-dr state. w hile in this state, upload the selected data register (selected by the present jtag instruction in the jtag instruction register) from the tdi input at the rising edge of tck. in order to remain in the shift-dr state, the tms input must be held low during input of all bits except the msb. the msb of the data is shifted in when this state is left by setting tms high. w hile the data register is sh ifted in from the tdi pin, the parallel inputs to the data register captured in the capture-dr state is shifted out on the tdo pin. ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. if the selected data register has a latched parallel-output, the latching takes place in the update-dr state. the exit-dr, pause-dr, and exit2-dr states are only used for navigating the state machine. as shown in the state diagram, the run-test/idle state need not be entered between selecting jtag instruction and using data registers, and some jtag instructions may select certain functions to be performed in the run-test/idle, making it unsuitable as an idle state. n ote: independent of the initial state of the tap c ontroller, the test-logic-r eset state can always be entered by holding tms high for five tck clock periods. for detailed information on the jtag specification, refer to the literature listed in ?bibliography? on page 301 . 27.4 using the b oundary-scan chain a complete description of the boundary-sc an capabilities are gi ven in the section ?ieee 1149.1 (jtag) boundary-scan? on page 302 . 27.5 using the on-c hip debug system as shown in figure 27-1 on page 297 , the hardware support for on-chip debugging consists mainly of: ? a scan chain on the interface between the internal avr cpu and the internal peripheral units ? break point unit ? communication interface between the cpu and jtag system all read or modify/write operations needed for implementing the debugger are done by applying avr instructions via the internal avr cpu scan chain. the cpu sends the result to an i/o memory mapped location which is part of the communication interface between the cpu and the jtag system. the break point unit implements break on change of program flow, single step break, two program memory break points, and two combined break points. together, the four break points can be configured as either: ? 4 single program memory break points ? 3 single program memory break point + 1 single data memory break point ? 2 single program memory break points + 2 single data memory break points ? 2 single program memory break points + 1 program memory break point with mask (?range break point?) ? 2 single program memory break points + 1 data memory break point with mask (?range break point?)
300 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 a debugger, like the avr studio, may however use one or more of these resources for its inter- nal purpose, leaving less flexibility to the end-user. a list of the on-chip debug specific jtag instructions is given in ?on-chip debug specific jtag instructions? on page 300 . the jtage n fuse must be programmed to enable the jtag test access port. in addition, the ocde n fuse must be programmed and no lock bits must be set for the on-chip debug system to work. as a security feature, the on-chip debug system is disabled when either of the lb1 or lb2 lock bits are set. otherwise, the on-chi p debug system would have provided a back-door into a secu red device. the avr studio ? enables the user to fully control execution of programs on an avr device with on-chip debug capability, avr in- circuit emulator, or the built-i n avr instruction set simulator. avr studio supports source level execution of assembly programs assembled with atmel cor- poration?s avr assembler and c programs compiled with third party vendors? compilers. avr studio runs under microsoft ? w indows ? 95/98/2000 and microsoft w indows n t ? . for a full description of the avr studio, please re fer to the avr studio user guide. only high- lights are presented in this document. all necessary execution commands are available in avr studio, both on source level and on disassembly level. the user can execute the program, single step through the code either by tracing into or stepping over functions, step out of functions, place the cursor on a statement and execute until the statement is reached, stop th e execution, and reset the execution target. in addition, the user can have an unlimited number of code break points (using the break instruction) and up to two data memory break points, alternatively combined as a mask (range) break point. 27.6 on-chip debug specific jtag instructions the on-chip debug support is considered being private jtag instructions, and distributed within atmel and to selected third party vendors only. instruction opcodes are listed for reference. 27.6.1 private0; 0x8 private jtag instruction for accessing on-chip debug system. 27.6.2 private1; 0x9 private jtag instruction for accessing on-chip debug system. 27.6.3 private2; 0xa private jtag instruction for accessing on-chip debug system. 27.6.4 private3; 0xb private jtag instruction for accessing on-chip debug system.
301 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 27.7 using the jtag pr ogramming capabilities programming of avr parts via jtag is performed via the 4-pin jtag port, tck, tms, tdi, and tdo. these are the only pins that need to be controlled/observed to perform jtag program- ming (in addition to power pins). it is not required to apply 12v externally. the jtage n fuse must be programmed and the jtd bit in the mcucr register must be cleared to enable the jtag test access port. the jtag programmi ng capability supports: ? flash programming and verifying ? eeprom programming and verifying ? fuse programming and verifying ? lock bit programming and verifying the lock bit security is exactly as in parallel programming mode. if the lock bits lb1 or lb2 are programmed, the ocde n fuse cannot be programmed unless first doing a chip erase. this is a security feature that ensures no back-door exists for reading out the content of a secured device. the details on programming through the jtag interface and programming specific jtag instructions are given in the section ?programming via the jtag interface? on page 354 . 27.8 bibliography for more information about general boundary-scan, the following literature can be consulted: ? ieee: ieee std. 1149.1-1990. ieee standard test access port and boundary-scan architecture, ieee, 1993 ? colin maunder: the board designers guide to testable logic circuits, addison- w esley, 1992 27.9 on-chip debug related register in i/o memory 27.9.1 ocdr ? on-chi p debug register the ocdr register provides a co mmunication channel from the running pr ogram in the micro- controller to the debugger. the cpu can transfer a byte to the debugger by writing to this location. at the same time, an in ternal flag; i/o debug register dirty ? idrd ? is set to indicate to the debugger that the register has been written. w hen the cpu reads the ocdr register the 7 lsb will be from the ocdr regi ster, while the msb is the idrd bit. the debugger clears the idrd bit when it has read the information. in some avr devices, this register is shared with a standard i/o location. in this case, the ocdr register can only be accessed if the ocde n fuse is programmed, and the debugger enables access to the ocdr register. in all other cases, the standard i/o location is accessed. refer to the debugger documentation for further information on how to use this register. bit 7 6543210 0x31 (0x51) msb/idrd lsb ocdr read/ w rite r/ w r/ w r/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0000000
302 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 28. ieee 1149.1 (jtag) boundary-scan 28.1 features ? jtag (ieee std. 1149.1 compliant) interface ? boundary-scan capabilities acco rding to the jtag standard ? full scan of all port functions as well as analog circuitry having off-chip connections ? supports the optional idcode instruction ? additional public avr_reset instruction to reset the avr 28.2 system overview the boundary-scan chain has the capability of drivin g and observing the logi c levels on the digi- tal i/o pins, as well as the boundary between digi tal and analog logic for analog circuitry having off-chip connections. at system level, all ics having jtag capabilities ar e connected serially by the tdi/tdo signals to form a long shift register. an external controller sets up the devices to drive values at their output pins, and observe the input values received from other devices. the controller compares the received data with the expected result. in this way, boundary-scan pro- vides a mechanism for testing interconnections and integrity of components on printed circuits boards by using the four tap signals only. the four ieee 1149.1 defined mandatory jtag in structions idcode, bypass, sample/pre- load, and extest, as well as the avr specif ic public jtag instruction avr_reset can be used for testing the print ed circuit board. initial scanning of the data register path will show the id-code of the device, since idcode is the default jtag instruction. it may be desirable to have the avr device in reset during test mode. if not reset, inputs to the device may be deter- mined by the scan operations, and the internal software may be in an undetermined state when exiting the test mode. en tering reset, the outputs of any po rt pin will instantly enter the high impedance state, making the highz instruction redundant. if needed, the bypass instruction can be issued to make the shortest possible scan chain through the device. the device can be set in the reset state either by pulling the external reset pin low, or issuing the avr_reset instruction with appropriate setting of the reset data register. the extest instruction is used for sampling external pins and loading output pins with data. the data from the output latch will be driven out on the pins as soon as the extest instruction is loaded into the jtag ir-register. therefore, the sample/preload should also be used for setting initial values to the scan ring, to avoid damaging the board when issuing the extest instruction for the first time. sample/preload c an also be used for taking a snapshot of the external pins during normal operation of the part. the jtage n fuse must be programmed and the jt d bit in the i/o register mcucr must be cleared to enable the jtag test access port. w hen using the jtag interface for boundary-scan, using a jtag tck clock frequency higher than the internal chip frequency is possible. the chip clock is not required to run. 28.3 data registers the data registers relevant for boundary-scan operations are: ? bypass register ? device identification register ? reset register ? boundary-scan chain
303 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 28.3.1 bypass register the bypass register consists of a single shift register stage. w hen the bypass register is selected as path between tdi and tdo, the register is reset to 0 when leaving the capture-dr controller state. the bypass register can be used to shorten the scan chain on a system when the other devices are to be tested. 28.3.2 device identification register figure 28-1 shows the structure of the de vice identification register. figure 28-1. the format of the device identification register 28.3.2.1 version version is a 4-bit number identifying the revision of the component. the jtag version number follows the revision of the device. revision a is 0x0, revision b is 0x1 and so on. 28.3.2.2 part number the part number is a 16-bit code identifying the component. the jtag part n umber for atmega640/1280/1281/2560/2561 is listed in table 30-6 on page 338 . 28.3.2.3 manufacturer id the manufacturer id is a 11-bit code identifying the manufacturer. the jtag manufacturer id for atmel is listed in table 30-6 on page 338 . 28.3.3 reset register the reset register is a test data register used to reset the part. since the avr tri-states port pins when reset, the reset register can also replace the function of the unimplemented optional jtag instruction highz. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high value present in the reset register. depending on the fuse set- tings for the clock options, the part will remain reset for a reset time-out period (see ?clock sources? on page 41 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 28-2 on page 304 . msb lsb bit 31 28 27 12 11 1 0 device id version part number manufacturer id 1 4 bits 16 bits 11 bits 1-bit
304 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 28-2. reset register 28.3.4 boundary-scan chain the boundary-scan chain has the capability of driv ing and observing the lo gic levels on the dig- ital i/o pins, as well as the boundary between di gital and analog logic for analog circuitry having off-chip connections. see ?boundary-scan chain? on page 305 for a complete description. 28.4 boundary-scan specifi c jtag instructions the instruction register is 4-bit wide, suppor ting up to 16 instructions. listed below are the jtag instructions useful for boundary-scan operation. n ote that the optional highz instruction is not implemented, but all outputs with tri-stat e capability can be set in high-impedant state by using the avr_reset instruction, since the initial state for all port pins is tri-state. as a definition in this datasheet, the lsb is shifted in and out first for all shift registers. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. 28.4.1 extest; 0x0 mandatory jtag instruction for selecting the boundary-scan chain as data register for testing circuitry external to the avr package. for port- pins, pull-up disable, output control, output data, and input data are all accessible in the scan chain. for analog ci rcuits having off-chip connections, the interface between the analog and th e digital logic is in the scan chain. the con- tents of the latched outputs of the boundary-scan chain is driven out as soon as the jtag ir- register is loaded with the extest instruction. the active states are: ? capture-dr : data on the external pins are sampled into the boundary-scan chain ? shift-dr : the internal scan chain is shifted by the tck input ? update-dr : data from the scan chain is applied to output pins 28.4.2 idcode; 0x1 optional jtag instruction selecting the 32-bit id-register as data register. the id-register consists of a version number, a device number and the manufacturer code chosen by jedec. this is the default inst ruction after power-up. dq from tdi clockdr avr_re s et to tdo from other internal and external reset s ources internal reset
305 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 the active states are: ? capture-dr : data in the idcode register is sampled into the boundary-scan chain ? shift-dr : the idcode scan chain is shifted by the tck input 28.4.3 sample_preload; 0x2 mandatory jtag instruction for pre-loading the output latches and taking a snap-shot of the input/output pins without affecting the system operation. however, the output latches are not connected to the pins. the boundary-scan chain is selected as data register. the active states are: ? capture-dr : data on the external pins are sampled into the boundary-scan chain ? shift-dr : the boundary-scan chain is shifted by the tck input ? update-dr : data from the boundary-scan chain is applied to the output latches. however, the output latches are not connected to the pins 28.4.4 avr_reset; 0xc the avr specific public jtag instruction for forcing the avr device into the reset mode or releasing the jtag reset source. the tap controller is not reset by this in struction. the one bit reset register is select ed as data register. n ote that the reset will be ac tive as long as there is a logic ?one? in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr : the reset register is shifted by the tck input 28.4.5 bypass; 0xf mandatory jtag instructio n selecting the bypass register for data register. the active states are: ? capture-dr : loads a logic ?0? into the bypass register ? shift-dr : the bypass register cell between tdi and tdo is shifted 28.5 boundary-scan chain the boundary-scan chain has the capability of drivin g and observing the logi c levels on the digi- tal i/o pins, as well as the boundary between digi tal and analog logic for analog circuitry having off-chip connection. 28.5.1 scanning the digital port pins figure 28-3 on page 306 shows the boundary-scan cell for a bi-directional port pin. the pull-up function is disabled during boundary-scan w hen the jtag ic contains extest or sample_preload. the cell consists of a bi-dir ectional pin cell that combines the three sig- nals output control - ocxn, output data - odxn, and input data - idxn, into only a two-stage shift register. the port and pin indexes are not used in the following description. the boundary-scan logic is not included in the figures in the datasheet. figure 28-4 on page 307 shows a simple digital port pin as described in the section ?i/o-ports? on page 70 . the bound- ary-scan details from figure 28-3 on page 306 replaces the dashed box in figure 28-4 on page 307 . w hen no alternate port function is present, the input data - id - corresponds to the pi n xn regis- ter value (but id has no synchronizer), output data corresponds to the port register, output
306 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 control corresponds to the data direction - dd register, and the pull-up enable - puexn - cor- responds to logic expression pud ddxn portxn. digital alternate port functions are connected outside the dotted box in figure 28-4 on page 307 to make the scan chain read the actual pin value. for analog function, there is a direct connec- tion from the external pin to the analog circuit. there is no scan chain on the interface between the digital and the analog circuitry, but some digi tal control signal to analog circuitry are turned off to avoid driving contention on the pads. w hen jtag ir contains extest or sample_preload the clock is not sent out on the port pins even if the ckout fuse is programmed. ev en though the clock is output when the jtag ir contains sample_preload, the clock is not sampled by the boundary scan. figure 28-3. boundary-scan cell for bi-directional port pin with pull-up function. dq dq g 0 1 0 1 dq dq g 0 1 0 1 0 1 port pin (pxn) vcc extest to next cell shiftdr output control (oc) output data (od) input data (id) from last cell updatedr clockdr ff1 ld1 ld0 ff0 0 1 pull-up enable (pue)
307 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 28-4. general port pin schematic diagram 28.5.2 scanning the reset pin the reset pin accepts 5v active low logic fo r standard reset operation, and 12v active high logic for high voltage parallel programming. an observe-only cell as shown in figure 28-5 is inserted for the 5v reset signal. figure 28-5. observe-only cell clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data bus sleep sleep: sleep control pxn i/o i/o see boundary-scan description for details! puexn ocxn odxn idxn puexn: pullup enable for pin pxn ocxn: output control for pin pxn odxn: output data to pin pxn idxn: input data from pin pxn 0 1 dq from previous cell clockdr s hiftdr to next cell from s ystem pin to s ystem logic ff1
308 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 28.6 boundary-scan related re gister in i/o memory 28.6.1 mcucr ? mcu control register the mcu control register contains control bits for general mcu functions. ? bits 7 ? jtd: jtag interface disable w hen this bit is zero, the jtag interface is enabled if the jtage n fuse is programmed. if this bit is one, the jtag interface is disabled. in or der to avoid unintentional disabling or enabling of the jtag interface, a timed sequence must be followed when changing this bit: the application software must write this bit to the desired value twice within four cycles to change its value. n ote that this bit must not be altered when using the on-chip debug system. 28.6.2 mcusr ? mcu status register the mcu status register provides information on which reset source caused an mcu reset. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. 28.7 atmega640/1280/1281/2560/ 2561 boundary-scan order table 28-1 on page 309 shows the scan order between tdi and tdo when the boundary-scan chain is selected as data path. bit 0 is the lsb; the first bit scanned in, and the first bit scanned out. the scan order follows the pin-out order as fa r as possible. therefore, the bits of port a and port k is scanned in the opposite bit order of the other ports. exceptions from the rules are the scan chains for the analog circuits, which constitute the most significant bits of the scan chain regardless of which physical pin they are connected to. in figure 28-3 on page 306 , pxn. data corresponds to ff0, pxn. control corresponds to ff1, pxn. bit 4, bit 5, bit 6 and bit 7 of port f is not in the scan chain, since these pins co nstitute the tap pins when the jtag is enabled. 28.8 boundary-scan description language files boundary-scan description language (bsdl) files describe boundary-scan capable devices in a standard format used by automated test-generation software. the order and function of bits in the boundary-scan data register are included in th is description. bsdl files are available for atmega1281/2561 and atmega640/1280/2560. bit 76543210 0x35 (0x55) jtd ? ? pud ? ? ivsel ivce mcucr read/ w rite r/ w rrr/ w rrr/ w r/ w initial value 00000000 bit 76543210 0x34 (0x54) ? ? ?jtrf wdrf borf extrf porf mcusr read/ w rite rrrr/ w r/ w r/ w r/ w r/ w initial value 0 0 0 see bit description
309 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 28-1. atmega640/1280/2560 boundary-scan order bit number signal name module 164 pg5.data port g 163 pg5.control 162 pe0.data port e 161 pe0.control 160 pe1.data 159 pe1.control 158 pe2.data 157 pe2.control 156 pe3.data 155 pe3.control 154 pe4.data 153 pe4.control 152 pe5.data 151 pe5.control 150 pe6.data 149 pe6.control 148 pe7.data 147 pe7.control 146 ph0.data port h 145 ph0.control 144 ph1.data 143 ph1.control 142 ph2.data 141 ph2.control 140 ph3.data 139 ph3.control 138 ph4.data 137 ph4.control 136 ph5.data 135 ph5.control 134 ph6.data 133 ph6.control
310 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 132 pb0.data port b 131 pb0.control 130 pb1.data 129 pb1.control 128 pb2.data 127 pb2.control 126 pb3.data 125 pb3.control 124 pb4.data 123 pb4.control 122 pb5.data 121 pb5.control 120 pb6.data 119 pb6.control 118 pb7.data 117 pb7.control 116 ph7.data port h 115 ph7.control 114 pg3.data port g 113 pg3.control 112 pg4.data 111 pg4.control 110 rstt reset logic (observe only) 109 pl0.data port l 108 pl0.control 107 pl1.data 106 pl1.control 105 pl2.data table 28-1. atmega640/1280/2560 boundary-scan order (continued) bit number signal name module
311 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 104 pl2.control 103 pl3.data 102 pl3.control 101 pl4.data 100 pl4.control 99 pl5.data 98 pl5.control 97 pl6.data 96 pl6.control 95 pl7.data 94 pl7.control 93 pd0.data port d 92 pd0.control 91 pd1.data 90 pd1.control 89 pd2.data 88 pd2.control 87 pd3.data 86 pd3.control 85 pd4.data 84 pd4.control 83 pd5.data 82 pd5.control 81 pd6.data 80 pd6.control 79 pd7.data 78 pd7.control 77 pg0.data port g 76 pg0.control 75 pg1.data 74 pg1.control 73 pc0.data port c 72 pc0.control 71 pc1.data 70 pc1.control 69 pc2.data table 28-1. atmega640/1280/2560 boundary-scan order (continued) bit number signal name module
312 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 68 pc2.control 67 pc3.data 66 pc3.control 65 pc4.data 64 pc4.control 63 pc5.data 62 pc5.control 61 pc6.data 60 pc6.control 59 pc7.data 58 pc7.control 57 pj0.data port j 56 pj0.control 55 pj1.data 54 pj1.control 53 pj2.data 52 pj2.control 51 pj3.data 50 pj3.control 49 pj4.data 48 pj4.control 47 pj5.data 46 pj5.control 45 pj6.data 44 pj6.control 43 pg2.data port g 42 pg2.control 41 pa7.data port a 40 pa7.control 39 pa6.data 38 pa6.control 37 pa5.data 36 pa5.control 35 pa4.data 34 pa4.control 33 pa3.data table 28-1. atmega640/1280/2560 boundary-scan order (continued) bit number signal name module
313 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32 pa3.control 31 pa2.data 30 pa2.control 29 pa1.data 28 pa1.control 27 pa0.data 26 pa0.control 25 pj7.data port j 24 pj7.control 23 pk7.data port k 22 pk7.control 21 pk6.data 20 pk6.control 19 pk5.data 18 pk5.control 17 pk4.data 16 pk4.control 15 pk3.data 14 pk3.control 13 pk2.data 12 pk2.control 11 pk1.data 10 pk1.control 9 pk0.data 8 pk0.control 7pf3.data port f 6 pf3.control 5pf2.data 4 pf2.control 3pf1.data 2 pf1.control 1pf0.data 0 pf0.control table 28-1. atmega640/1280/2560 boundary-scan order (continued) bit number signal name module
314 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 28-2. atmega1281/2561 boundary-scan order bit number signal name module 100 pg5.data port g 99 pg5.control 98 pe0.data port e 97 pe0.control 96 pe1.data 95 pe1.control 94 pe2.data 93 pe2.control 92 pe3.data 91 pe3.control 90 pe4.data 89 pe4.control 88 pe5.data 87 pe5.control 86 pe6.data 85 pe6.control 84 pe7.data 83 pe7.control 82 pb0.data port b 81 pb0.control 80 pb1.data 79 pb1.control 78 pb2.data 77 pb2.control 76 pb3.data 75 pb3.control 74 pb4.data 73 pb4.control 72 pb5.data 71 pb5.control 70 pb6.data 69 pb6.control 68 pb7.data 67 pb7.control 66 pg3.data port g
315 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 65 pg3.control 64 pg4.data 63 pg4.control 62 rstt reset logic (observe only) 61 pd0.data port d 60 pd0.control 59 pd1.data 58 pd1.control 57 pd2.data 56 pd2.control 55 pd3.data 54 pd3.control 53 pd4.data 52 pd4.control 51 pd5.data 50 pd5.control 49 pd6.data 48 pd6.control 47 pd7.data 46 pd7.control 45 pg0.data port g 44 pg0.control 43 pg1.data 42 pg1.control 41 pc0.data port c 40 pc0.control 39 pc1.data 38 pc1.control 37 pc2.data 36 pc2.control 35 pc3.data 34 pc3.control 33 pc4.data 32 pc4.control 31 pc5.data 30 pc5.control table 28-2. atmega1281/2561 boundary-scan order (continued) bit number signal name module
316 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29 pc6.data 28 pc6.control 27 pc7.data 26 pc7.control 25 pg2.data port g 24 pg2.control 23 pa7.data port a 22 pa7.control 21 pa6.data 20 pa6.control 19 pa5.data 18 pa5.control 17 pa4.data 16 pa4.control 15 pa3.data 14 pa3.control 13 pa2.data 12 pa2.control 11 pa1.data 10 pa1.control 9pa0.data 8pa0.control 7pf3.data port f 6 pf3.control 5pf2.data 4 pf2.control 3pf1.data 2 pf1.control 1pf0.data 0 pf0.control table 28-2. atmega1281/2561 boundary-scan order (continued) bit number signal name module
317 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29. boot loader support ? read -while-write self-programming the boot loader support provides a real read- w hile- w rite self-programming mechanism for downloading and uploading program code by the m cu itself. this feature a llows flexible applica- tion software updates controlled by the mcu using a flash-resident boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program mem- ory. the program code within the boot loader section has the capability to write into the entire flash, including the boot loader memory. the b oot loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and t he boot loader has two separate sets of boot lock bits which can be set indepen dently. this gives the user a uniq ue flexibility to select differ- ent levels of protection. 29.1 features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficient algorithm ? efficient read-modify-write support n ote: 1. a page is a section in the flas h consisting of several bytes (see table 30-7 on page 338 ) used during programming. the page organization does not affect normal operation. 29.2 application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 29-2 on page 320 ). the size of the different sections is configured by the bootsz fuses as shown in table 29-7 on page 328 and figure 29-2 on page 320 . these two sections can have different level of protecti on since they have different sets of lock bits. 29.2.1 application section the application section is the section of the flash that is used for storing the application code. the protection level for the application section can be selected by the application boot lock bits (boot lock bits 0), see table 29-2 on page 321 . the application section can never store any boot loader code since the spm instruction is disabled when executed from the application section. 29.2.2 bls ? boot loader section w hile the application section is used for storing the application code, the the boot loader soft- ware must be located in the bls since the spm instruction can initiate a programming when executing from the bls only. the spm instruct ion can access the entire flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 29-3 on page 321 . 29.3 read-while-write and no r ead-while-write flash sections w hether the cpu supports read- w hile- w rite or if the cpu is halted during a boot loader soft- ware update is dependent on which address that is being programmed. in addition to the two sections that are configurable by the bootsz fuses as described above, the flash is also
318 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 divided into two fixed sections, the read- w hile- w rite (r ww ) section and the n o read- w hile- w rite ( n r ww ) section. the limit between the r ww - and n r ww sections is given in table 29- 1 and figure 29-1 on page 319 . the main difference between the two sections is: ? w hen erasing or writing a page located inside the r ww section, the n r ww section can be read during the operation ? w hen erasing or writing a page located inside the n r ww section, the cpu is halted during the entire operation n ote that the user software can never read any code that is located inside the r ww section dur- ing a boot loader software operation. the syntax ?read- w hile- w rite section? refers to which section that is being programmed (erased or written), not which section that actually is being read during a boot loader software update. 29.3.1 rww ? read-while-write section if a boot loader software update is programming a page inside the r ww section, it is possible to read code from the flash, but only code that is located in the n r ww section. during an on- going programming, the software must ensure that the r ww section never is being read. if the user software is trying to read code that is located inside the r ww section (that is, by load pro- gram memory, call, or jump instructions or an interrupt) during programming, the software might end up in an unknown state. to avoid this, the in terrupts should either be disabled or moved to the boot loader section. the boot loader section is always located in the n r ww section. the r ww section busy bit (r ww sb) in the store program memory control and status register (spmcsr) will be read as lo gical one as long as the r ww section is blocked for reading. after a programming is completed, the r ww sb must be cleared by software before reading code located in the r ww section. see ?spmcsr ? store program memory control and status reg- ister? on page 332. for details on how to clear r ww sb. 29.3.2 nrww ? no read-while-write section the code located in the n r ww section can be read when the boot loader software is updating a page in the r ww section. w hen the boot loader code updates the n r ww section, the cpu is halted during the entire page erase or page w rite operation. table 29-1. read- w hile- w rite features which section does the z-pointer address during the programming? which section can be read during programming? cpu halted? read-while-write supported? r ww section n r ww section n oyes n r ww section n one yes n o
319 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 29-1. read- w hile- w rite vs. n o read- w hile- w rite read-while-write (rww) s ection no read-while-write (nrww) s ection z-pointer addresses rww s ection z-pointer addresses nrww s ection cpu is halted during the operation code located in nrww s ection can be read during the operation
320 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 29-2. memory sections n ote: 1. the parameters in the figure above are given in table 29-7 on page 328 . 29.4 boot loader lock bits if no boot loader capability is n eeded, the entire flash is available for application code. the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to sele ct different levels of protection. the user can select: ? to protect the entire flash from a software update by the mcu ? to protect only the boot loader flash section from a software update by the mcu ? to protect only the application flash section from a software update by the mcu ? allow software update in the entire flash see table 29-2 on page 321 and table 29-3 on page 321 for further details. the boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip erase command only. the general w rite lock (lock bit mode 2) does not control the pro- gramming of the flash memory by spm instruction. similarly, the general read/ w rite lock (lock bit mode 1) does not control reading nor writing by (e)lpm/spm, if it is attempted. 0x0000 flashend program memory bootsz = '11' application flash s ection boot loader flash s ection flashend program memory bootsz = '10' 0x0000 program memory bootsz = '01' program memory bootsz = '00' application flash s ection boot loader flash s ection 0x0000 flashend application flash s ection flashend end rww s tart nrww application flash s ection boot loader flash s ection boot loader flash s ection end rww s tart nrww end rww s tart nrww 0x0000 end rww, end application s tart nrww, s tart boot loader application flash s ection application flash s ection application flash s ection read-while-write s ection no read-while-write s ection read-while-write s ection no read-while-write s ection read-while-write s ection no read-while-write s ection read-while-write s ection no read-while-write s ection end application s tart boot loader end application s tart boot loader end application s tart boot loader
321 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. ?1? means unprogrammed, ?0? means programmed. n ote: 1. ?1? means unprogrammed, ?0? means programmed. 29.4.1 entering the boot loader program entering the boot loader takes place by a jump or call from the application program. this may be initiated by a trigger such as a command received via usart, or spi interface. alternatively, the boot reset fuse can be programmed so that the reset vector is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the applica- tion code is loaded, the program can st art executing the application code. n ote that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse is pro- grammed, the reset vector will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. n ote: 1. ?1? means unprogrammed, ?0? means programmed. table 29-2. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 n o restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application sectio n. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application sectio n. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 29-3. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 n o restrictions for spm or (e)l pm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the b oot loader section. 401 (e)lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the b oot loader section. table 29-4. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset (see table 29-7 on page 328 )
322 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.5 addressing the flash during self-programming the z-pointer is used to address the spm commands. the z pointer consists of the z-registers zl and zh in the register file, and rampz in the i/o space. the number of bits actually used is implementation dependent. n ote that the rampz register is only implemented when the pro- gram space is larger than 64kbytes. since the flash is organized in pages (see table 30-7 on page 338 ), the program counter can be treated as having two different sections. one sect ion, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 29-3 . n ote that the page erase and page w rite operations are addressed independently. therefore it is of major importance that the boot loader software addresses the same page in both the page erase and page w rite operation. once a program- ming operation is initiated, the address is latched and the z-pointer can be used for other operations. the (e)lpm instruction use the z-pointer to st ore the address. since this instruction addresses the flash byte-by-byte, also bit z0 of the z-pointer is used. figure 29-3. addressing the flash during spm (1) n ote: 1. the different variables used in figure 29-3 are listed in table 29-9 on page 329 . bit 2322212019181716 15 14 13 12 11 10 9 8 rampz rampz7 rampz6 rampz5 rampz4 rampz3 rampz2 rampz1 rampz0 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30)z7z6z5z4z3z2z1z0 76543210 program memory 0 1 15 z - regi s ter bit 0 zpagem s b word addre ss within a page page addre ss within the fla s h zpcm s b in s truction word pag e pcword[pagem s b:0]: 00 01 02 pageend pag e pcword pcpage pcm s b pagem s b program counter
323 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.6 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buf- fer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page w rite operation: alternative 1, fill the bu ffer before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page w rite alternative 2, fill the bu ffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page w rite if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. w hen using alternative 1, the boot loader provides an effective read-modify- w rite feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alter- native 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page w rite operation is addressing the same page. see ?simple assembly code example for a boot loader? on page 327 for an assembly code example. 29.6.1 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?x0000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation. ? page erase to the r ww section: the n r ww section can be read during the page erase ? page erase to the n r ww section: the cpu is halted during the operation 29.6.2 filling the temporary buffer (page loading) to write an instruction word, set up the address in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the content of pc w ord in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page w rite operation or by writing the r ww sre bit in spmcsr. it is also erased after a system reset. n ote that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in the middle of an spm page load oper ation, all data loaded is still buffered.
324 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.6.3 performing a page write to execute page w rite, set up the address in the z-pointer, write ?x0000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. ? page w rite to the r ww section: the n r ww section can be read during the page w rite ? page w rite to the n r ww section: the cpu is halted during the operation 29.6.4 using the spm interrupt if the spm interrupt is en abled, the spm interrupt will genera te a constant in terrupt when the spme n bit in spmcsr is cleared. this means that the interrupt can be us ed instead of polling the spmcsr register in software. w hen using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an interrupt is accessing the r ww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 105 . 29.6.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to program the boot lock bit11 to protect the boot loader software from any internal software changes. 29.6.6 prevent reading the rww section during self-programming during self-programming (either page erase or page w rite), the r ww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self programming operation. the r ww sb in the spmcsr will be set as long as the r ww section is busy. during self-programming the interrupt vector table should be moved to the bls as described in ?interrupts? on page 105 , or the interrupts must be disabled. before addressing the r ww section after the programming is completed, the user software must clear the r ww sb by writing the r ww sre. see ?simple assembly code example for a boot loader? on page 327 for an example. 29.6.7 setting the boot loader lock bits by spm to set the boot loader lock bits and general lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four clock cycles after writing spmcsr. see table 29-2 on page 321 and table 29-3 on page 321 for how the different settings of the boot loader bits affect the flash access. if bits 5:0 in r0 are cleare d (zero), the corresponding loc k bit will be programmed if an spm instruction is executed within fo ur cycles after blbset and spme n are set in spmcsr. the z- pointer is don?t care during this operation, but fo r future compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lo ck bits). for future compatibility it is also recommended to set bits 7 and 6 in r0 to ?1? when writing the lock bits. w hen program- ming the lock bits the entire flas h can be read during the operation. bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 lb2 lb1
325 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.6.8 eeprom write prevents writing to spmcsr n ote that an eeprom writ e operation will block all software pr ogramming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operation. it is recommended that the user checks the status bit (eepe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 29.6.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and spme n bits in spmcsr. w hen an (e)lpm instruction is executed within three cpu cycles after the blbset and spme n bits are set in spmcsr, the value of the lock bi ts will be loaded in the desti nation register. the blbset and spme n bits will auto-clear upon completi on of reading the lock bits or if no (e)lpm instruction is executed within three cpu cycles or no spm instruction is executed within four cpu cycles. w hen blbset and spme n are cleared, (e)lpm will work as described in the instruction set manual . the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and spme n bits in spmcsr. w hen an (e)lpm instruction is executed within three cycles after the blbset and spme n bits are set in the spmcsr, the va lue of the fuse low byte (flb) will be loaded in the destination register as shown below. refer to table 30-5 on page 337 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. w hen an (e)lpm instruction is executed within three cycles after the blbset and spme n bits are set in the spmcsr, the value of the fuse high byte (fhb ) will be loaded in the destination register as shown below. refer to table 30-4 on page 337 for detailed description and mapping of the fuse high byte. w hen reading the extended fuse byte, load 0x0002 in the z-pointer. w hen an (e)lpm instruc- tion is executed within three cycles after the blbset and spme n bits are set in the spmcsr, the value of the exten ded fuse byte (efb) will be loaded in the destination r egister as shown below. refer to table 30-3 on page 336 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. 29.6.10 reading the signature row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 29-5 on page 326 and set the sigrd and spme n bits in spmcsr. w hen an lpm instruction is executed within three cpu cycles after the sigrd and spme n bits are set in bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0 bit 76543210 rd ? ? ? ? ? efb2 efb1 efb0
326 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 spmcsr, the signature byte valu e will be loaded in the destin ation register. the sigrd and spme n bits will auto-clear upon completion of readi ng the signature row lo ck bits or if no lpm instruction is executed within three cpu cycles. w hen sigrd and spme n are cleared, lpm will work as described in the instruction set manual . n ote: all other addresses are reserved for future use. 29.6.11 preventing flash corruption during periods of low v cc , the flash program can be corrupted because the supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situ ations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate correctly. secondly, the cpu itself can execute instruct ions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr reset active (low) during peri ods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating volt- age matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operatio n is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will pre- vent the cpu from attempting to decode and execute instructions, effectively protecting the spmcsr register and thus the flash from unintentional writes. 29.6.12 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 29-6 shows the typical pro- gramming time for flash accesses from the cpu. table 29-5. signature row addressing signature byte z-pointer address device signature byte 1 0x0000 device signature byte 2 0x0002 device signature byte 3 0x0004 rc oscillator calibration byte 0x0001 table 29-6. spm programming time symbol min programming time max programming time flash write (page erase, page w rite, and write lock bits by spm) 3.7ms 4.5ms
327 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.6.13 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 328 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ; return to rww section ; verify that rww section is safe to read return: in temp1, spmcsr sbrs temp1, rwwsb ; if rwwsb is set, the rww section is not ready yet ret ; re-enable the rww section ldi spmcrval, (1< 329 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. for details about these two section, see ? n r ww ? n o read- w hile- w rite section? on page 318 and ?r ww ? read- w hile- w rite section? on page 318 . n ote: 1. z0: should be zero for all spm commands, byte select for the (e)lpm instruction. 2. see ?addressing the flash during self-programming? on page 322 for details about the use of z-pointer during self-programming. table 29-8. read- w hile- w rite limit, atmega640 section (1) pages address read- w hile- w rite section (r ww ) 224 0x0000 - 0x6fff n o read- w hile- w rite section ( n r ww ) 32 0x7000 - 0x7fff table 29-9. explanation of different variables used in figure 29-3 on page 322 and the map- ping to the z-pointer, atmega640 variable corresponding z-value (2) description (1) pcmsb 14 most significant bit in the program counter. (the program counter is 15 bits pc[14:0]). pag e m s b 6 most significant bit which is used to address the words within one page (128 words in a page requires seven bits pc [6:0]). zpcmsb z15 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z7 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[14:7] z15:z8 program counter page address: page select, for page erase and page w rite. pc w ord pc[6:0] z7:z1 program counter word address: w ord select, for filling temporary buffer (must be zero during page w rite operation).
330 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 29.6.15 atmega1280/1281 boot loader parameters in table 29-10 and table 29-11 , the parameters used in the description of the self-programming are given. n ote: 1. the different bootsz fuse configurations are shown in figure 29-2 on page 320 . n ote: 1. for details about these two section, see ? n r ww ? n o read- w hile- w rite section? on page 318 and ?r ww ? read- w hile- w rite section? on page 318 . table 29-10. boot size configuration, atmega1280/1281 (1) bootsz1 bootsz0 boot size pages appli-cation flash section boot loader flash section end application section boot reset address (start boot loader section) 11 512 words 4 0x0000 - 0xfdff 0xfe00 - 0xffff 0xfdff 0xfe00 10 1024 words 8 0x0000 - 0xfbff 0xfc00 - 0xffff 0xfbff 0xfc00 01 2048 words 16 0x0000 - 0xf7ff 0xf800 - 0xffff 0xf7ff 0xf800 00 4096 words 32 0x0000 - 0xefff 0xf000 - 0xffff 0xefff 0xf000 table 29-11. read- w hile- w rite limit, atmega1280/1281 section (1) pages address read- w hile- w rite section (r ww ) 480 0x0000 - 0xefff n o read- w hile- w rite section ( n r ww ) 32 0xf000 - 0xffff table 29-12. explanation of different variables used in figure 29-3 on page 322 and the map- ping to the z-pointer, atmega1280/1281 variable corresponding z-value (2) description (1) pcmsb 15 most significant bit in the program counter. (the program counter is 16 bits pc[15:0])
331 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. z0: should be zero for all spm command s, byte select for t he (e)lpm instruction. 2. see ?addressing the flash during self-programming? on page 322 for details about the use of z-pointer during self-programming. 3. the z-register is only 16 bits wide. bit 16 is located in the rampz register in the i/o map. 29.6.16 atmega2560/2561 boot loader parameters in table 29-13 through table 29-15 on page 332 , the parameters used in the description of the self-programming are given. n ote: 1. the different bootsz fuse configurations are shown in figure 29-2 on page 320 . pag e m s b 6 most significant bit which is used to address the words within one page (128 words in a page requires seven bits pc [6:0]). zpcmsb z16 (3) bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z7 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[15:7] z16 (3) :z8 program counter page address: page select, for page erase and page w rite pc w ord pc[6:0] z7:z1 program counter word address: w ord select, for filling temporary buffer (must be zero during page w rite operation) table 29-12. explanation of different variables used in figure 29-3 on page 322 and the map- ping to the z-pointer, atmega1280/1281 (continued) variable corresponding z-value (2) description (1) table 29-13. boot size configuration, atmega2560/2561 (1) bootsz1 bootsz0 boot size pages appli-cation flash section boot loader flash section end application section boot reset address (start boot loader section) 11 512 words 4 0x00000 - 0x1fdff 0x1fe00 - 0x1ffff 0x1fdff 0x1fe00 10 1024 words 8 0x00000 - 0x1fbff 0x1fc00 - 0x1ffff 0x1fbff 0x1fc00 01 2048 words 16 0x00000 - 0x1f7ff 0x1f800 - 0x1ffff 0x1f7ff 0x1f800 00 4096 words 32 0x00000 - 0x1efff 0x1f000 - 0x1ffff 0x1efff 0x1f000
332 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: 1. for details about these two section, see ? n r ww ? n o read- w hile- w rite section? on page 318 and ?r ww ? read- w hile- w rite section? on page 318 . n otes: 1. z0: should be zero for all spm command s, byte select for t he (e)lpm instruction. 2. see ?addressing the flash during self-programming? on page 322 for details about the use of z-pointer during self-programming. 3. the z-register is only 16 bits wide. bit 16 is located in the rampz register in the i/o map. 29.7 register description 29.7.1 spmcsr ? store program memory control and status register the store program memory control and status register contains the control bits needed to con- trol the boot loader operations. ? bit 7 ? spmie: spm interrupt enable w hen the spmie bit is written to one, and the i-bit in the status register is set (one), the spm ready interrupt will be enabled. the spm ready in terrupt will be ex ecuted as long as the spme n bit in the spmcsr register is cleared. table 29-14. read- w hile- w rite limit, atmega2560/2561 section (1) pages address read- w hile- w rite section (r ww ) 992 0x00000 - 0x1efff n o read- w hile- w rite section ( n r ww ) 32 0x1f000 - 0x1ffff table 29-15. explanation of different variables used in figure 29-3 on page 322 and the map- ping to the z-pointer, atmega2560/2561 variable corresponding z-value (2) description (1) pcmsb 16 most significant bit in the program counter. (the program counter is 17 bits pc[16:0]). pag e m s b 6 most significant bit which is used to address the words within one page (128 words in a page requires seven bits pc [6:0]). zpcmsb z17:z16 (3) bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z7 bit in z-pointer that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[16:7] z17 (3) :z8 program counter page address: page select, for page erase and page w rite. pc w ord pc[6:0] z7:z1 program counter word address: w ord select, for filling temporary buffer (must be zero during page w rite operation). bit 7 6 5 4 3 2 1 0 0x37 (0x57) spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen spmcsr read/ w rite r/ w rr/ w r/ w r/ w r/ w r/ w r/ w initial value 0 0 0 0 0 0 0 0
333 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 6 ? rwwsb: read-while-write section busy w hen a self-programming (page erase or page w rite) operation to the r ww section is initi- ated, the r ww sb will be set (one) by hardware. w hen the r ww sb bit is set, the r ww section cannot be accessed. the r ww sb bit will be cleared if the r ww sre bit is written to one after a self-programming operation is completed. alternatively the r ww sb bit will automatically be cleared if a page load operation is initiated. ? bit 5 ? sigrd: signature row read if this bit is written to one at the same time as spme n , the next lpm instruction within three clock cycles will read a byte from the signatu re row into the dest ination register. see ?reading the signature row from software? on page 325 for details. an spm inst ruction within four cycles after sigrd and spme n are set will have no effect. this operation is reserved for future use and should not be used. ? bit 4 ? rwwsre: read-while-write section read enable w hen programming (page erase or page w rite) to the r ww section, the r ww section is blocked for reading (the r ww sb will be set by hardware). to re-enable the r ww section, the user software must wait until the programming is completed (spme n will be cleared). then, if the r ww sre bit is written to one at the same time as spme n , the next spm instruction within four clock cycles re-enables the r ww section. the r ww section cannot be re-enabled while the flash is busy with a page erase or a page w rite (spme n is set). if the r ww sre bit is writ- ten while the flash is being loaded, the flas h load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spme n , the next spm instruction within four clock cycles sets boot lock bits, according to the data in r0. the data in r1 and the address in the z- pointer are ignored. the blbset bit will autom atically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an (e)lpm instruction within th ree cycles after blbset and spme n are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in th e z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 325 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spme n , the next spm instruction within four clock cycles executes page w rite, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pg w rt bit will auto-clear upon co mpletion of a page w rite, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page w rite operation if the n r ww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spme n , the next spm instruction within four clock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bi t will auto-clear upon comp letion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page w rite operation if the n r ww section is addressed.
334 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either r ww sre, blbset, pg w rt? or pgers, the following spm instruction will have a spe- cial meaning, see description above. if only spme n is written, the follo wing spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spme n bit will auto-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. during page erase and page w rite, the spme n bit remains high until the operation is completed. w riting any other combination than ?10001?, ?01001?, ?00101?, ?00011? or ?00001? in the lower five bits will have no effect. n ote: only one spm instruction should be active at any time.
335 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30. memory programming 30.1 program and data memory lock bits the atmega640/1280/1281/2560/2561 provides six lock bits which can be left unprogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 30-2 . the lock bits can only be erased to ?1? with the chip erase command. n ote: 1. ?1? means unprogrammed, ?0? means programmed table 30-1. lock bit byte (1) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 5 boot lock bit 1 (unprogrammed) blb11 4 boot lock bit 1 (unprogrammed) blb02 3 boot lock bit 1 (unprogrammed) blb01 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 30-2. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 111 n o memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parallel and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 111 n o restrictions for spm or (e)lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 (e)lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section.
336 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed. 30.2 fuse bits the atmega640/1280/1281/2560/2561 has three fuse bytes. table 30-3 through table 30-5 on page 337 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. n ote that the fuses are read as logical zero, ?0?, if they are programmed. n ote: 1. see ?system and reset characteristics? on page 372 for bodlevel fuse decoding. blb1 mode blb12 blb11 111 n o restrictions for spm or (e)lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and (e)lpm executing from the application section is not allowed to read from the boot loader sect ion. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 (e)lpm executing from the application section is not allowed to read from the boot loader sect ion. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 30-2. lock bit protection modes (1)(2) (continued) memory lock bits protection type table 30-3. extended fuse byte extended fuse byte bit no description default value ?7 ? 1 ?6 ? 1 ?5 ? 1 ?4 ? 1 ?3 ? 1 bodlevel2 (1) 2 brown-out detector trigger level 1 (unprogrammed) bodlevel1 (1) 1 brown-out detector trigger level 1 (unprogrammed) bodlevel0 (1) 0 brown-out detector trigger level 1 (unprogrammed)
337 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. the spie n fuse is not accessible in serial programming mode. 2. the default value of bootsz1:0 results in maximum boot size. see table 29-7 on page 328 for details. 3. see ? w dtcsr ? w atchdog timer control register? on page 67 for details. 4. n ever ship a product with the ocde n fuse programmed regardless of the setting of lock bits and jtage n fuse. a programmed ocde n fuse enables some parts of the clock system to be running in all sleep modes. this may increase the power consumption. n otes: 1. the default value of sut1:0 results in maxi mum start-up time for the default clock source. see ?system and reset characteristics? on page 372 for details. 2. the default setting of cksel3:0 results in internal rc oscillator @ 8 mhz. see table 10-1 on page 41 for details. 3. the ckout fuse allow the system cl ock to be output on porte7. see ?clock output buffer? on page 49 for details. 4. see ?system clock prescaler? on page 49 for details. the status of the fuse bits is not affected by chip erase. n ote that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. table 30-4. fuse high byte fuse high byte bit no description default value ocde n (4) 7 enable ocd 1 (unprogrammed, ocd disabled) jtage n 6 enable jtag 0 (programmed, jtag enabled) spie n (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) w dto n (3) 4 w atchdog timer always on 1 (unprogrammed) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bootsz1 2 select boot size (see table 30-9 on page 339 for details) 0 (programmed) (2) bootsz0 1 select boot size (see table 30-9 on page 339 for details) 0 (programmed) (2) bootrst 0 select reset vector 1 (unprogrammed) table 30-5. fuse low byte fuse low byte bit no description default value ckdiv8 (4) 7 divide clock by 8 0 (programmed) ckout (3) 6 clock output 1 (unprogrammed) sut1 5 select start-up time 1 (unprogrammed) (1) sut0 4 select start-up time 0 (programmed) (1) cksel3 3 select clock source 0 (programmed) (2) cksel2 2 select clock source 0 (programmed) (2) cksel1 1 select clock source 1 (unprogrammed) (2) cksel0 0 select clock source 0 (programmed) (2)
338 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.2.1 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuse s are also latched on power-up in n ormal mode. 30.3 signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega640/1280/1281/2560/2561 the signa- ture bytes are given in table 30-6 . 30.4 calibration byte the atmega640/1280/1281/2560/2561 has a byte calibration value for the internal rc oscilla- tor. this byte resides in t he high byte of address 0x000 in the signature address space. during reset, this byte is automatically written into the osccal register to ensure correct frequency of the calibrated rc oscillator. 30.5 page size 30.6 parallel programming paramete rs, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bits in the atmega640/1280/1281/2560/2561. pulses are assumed to be at least 250ns unless otherwise noted. table 30-6. device and jtag id part signature bytes address jtag 0x000 0x001 0x002 part number manufacture id atmega640 0x1e 0x96 0x08 9608 0x1f atmega1280 0x1e 0x97 0x03 9703 0x1f atmega1281 0x1e 0x97 0x04 9704 0x1f atmega2560 0x1e 0x98 0x01 9801 0x1f atmega2561 0x1e 0x98 0x02 9802 0x1f table 30-7. n o. of w ords in a page and n o. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 128k words (256kbytes) 128 words pc[6:0] 1024 pc[16:7] 16 table 30-8. n o. of w ords in a page and n o. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 4kbytes 8 bytes eea[2:0] 512 eea[11:3] 11
339 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.6.1 signal names in this section, some pins of the atmega640/1280/1281/2560/2561 are referenced by signal names describing their functionality during parallel programming, see figure 30-1 and table 30- 9 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a positive pulse. the bit coding is shown in table 30-12 on page 340 . w hen pulsing w r or oe , the command loaded determines the action executed. the different commands are shown in table 30-13 on page 340 . figure 30-1. parallel programming (1) n ote: 1. unused pins should be left floating. table 30-9. pin n ame mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming, 1: device is ready for new command oe pd2 i output enable (active low) w r pd3 i w rite pulse (active low) bs1 pd4 i byte select 1 xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 pagel pd7 i program memory and eeprom data page load bs2 pa0 i byte select 2 data pb7-0 i/o bi-directional data bus (output when oe is low ) vcc +5v gnd xt al1 pd1 pd2 pd3 pd4 pd5 pd6 pb7 - pb0 data re s et pd7 +12v b s 1 xa0 xa1 oe rd y/ b s y pagel pa0 wr b s 2 avcc +5v
340 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 30-10. bs2 and bs1 encoding bs2 bs1 flash / eeprom address flash data loading / reading fuse programming reading fuse and lock bits 0 0 low byte low byte low byte fuse low byte 0 1 high byte high byte high byte lockbits 10 extended high byte reserved extended byte extended fuse byte 1 1 reserved reserved reserved fuse high byte table 30-11. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 30-12. xa1 and xa0 enoding xa1 xa0 action when xtal1 is pulsed 0 0 load flash or eeprom address (high or low address byte determined by bs2 and bs1) 0 1 load data (high or low data byte for flash determined by bs1) 1 0 load command 11 n o action, idle table 30-13. command byte bit encoding command byte command executed 1000 0000 chip erase 0100 0000 w rite fuse bits 0010 0000 w rite lock bits 0001 0000 w rite flash 0001 0001 w rite eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom
341 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.7 parallel programming 30.7.1 enter programming mode the following algorithm puts the devi ce in parallel programming mode: 1. apply 4.5v - 5.5v between v cc and g n d. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 30-11 on page 340 to ?0000? and wait at least 100ns. 4. apply 11.5v - 12.5v to reset . any activity on prog_enable pins within 100ns after +12v has been applied to reset , will cause the device to fa il entering programming mode. 5. w ait at least 50s before sending a new command. 30.7.2 considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations ? skip writing the data value 0xff, that is t he contents of the enti re eeprom (unless the eesave fuse is programmed) and flash after a chip erase ? address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom. this consideration also applies to signature bytes reading 30.7.3 chip erase the chip erase will erase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be perfor med before the flas h and/or eeprom are reprogrammed. n ote: 1. the eeprpom memory is preserved during chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give w r a negative pulse. this starts the chip erase. rdy/bsy goes low. 6. w ait until rdy/bsy goes high before loading a new command. 30.7.4 programming the flash the flash is organized in pages, see table 30-7 on page 338 . w hen programming the flash, the program data is latched into a page buffer. this allows one page of program data to be pro- grammed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ? w rite flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?.
342 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 3. set data to ?0001 0000?. this is the command for w rite flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte (address bits 7:0) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?00?. this selects the address low byte. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. see figure 30-3 on page 343 for signal waveforms. f. repeat b through e until the entire buffer is filled or until all data within the page is loaded w hile the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash . this is illustrated in figure 30-2 on page 343 . n ote that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page w rite. g. load address high byte (address bits15:8) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?01?. this selects the address high byte. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. load address extended high byte (address bits 23:16) 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs2, bs1 to ?10?. this selects the address extended high byte. 3. set data = address extended high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. i. program page 1. set bs2, bs1 to ?00?. 2. give w r a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low. 3. w ait until rdy/bsy goes high (see figure 30-3 on page 343 for signal waveforms). j. repeat b through i until the entire flash is programmed or until all data has been programmed
343 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 k. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for n o operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. figure 30-2. addressing the flash w hich is organized in pages (1) n ote: 1. pcpage and pc w ord are listed in table 30-7 on page 338 . figure 30-3. programming the flash w aveforms (1) n ote: 1. ?xx? is don?t care. the letters re fer to the programming description above. 30.7.5 programming the eeprom the eeprom is organized in pages, see table 30-8 on page 338 . w hen programming the eeprom, the program data is latche d into a page buffer. this al lows one page of data to be programmed simultaneously. th e programming algorithm for th e eeprom data memory is as program memory word addre ss within a page page addre ss within the fla s h in s truction word pag e pcword[pagem s b:0]: 00 01 02 pageend pag e pcword pcpage pcm s b pagem s b program counter rdy/b s y wr oe re s et +12v pagel b s 2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 b s 1 xtal1 xx xx xx abcdeb cdeg f addr. ext.h h i
344 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 follows (refer to ?programming the flash? on page 341 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled l: program eeprom page 1. set bs2, bs1 to ?00?. 2. give w r a negative pulse. this starts pr ogramming of the eeprom page. rdy/bsy goes low. 3. w ait until to rdy/bsy goes high before programming the next page (see figure 30-4 for signal waveforms). figure 30-4. programming the eeprom w aveforms 30.7.6 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 341 for details on command and address loading): 1. a: load command ?0000 0010?. 2. h: load address extended byte (0x00- 0xff). 3. g: load address high byte (0x00 - 0xff). 4. b: load address low byte (0x00 - 0xff). 5. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 6. set bs to ?1?. the flash word high byte can now be read at data. 7. set oe to ?1?. rdy/b s y wr oe re s et +12v pagel b s 2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 b s 1 xtal1 xx agbceb c el k
345 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.7.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 341 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 30.7.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 341 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give w r a negative pulse and wait for rdy/bsy to go high. 30.7.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 341 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs2, bs1 to ?01?. this selects high data byte. 4. give w r a negative pulse and wait for rdy/bsy to go high. 5. set bs2, bs1 to ?00?. this selects low data byte. 30.7.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?programming the flash? on page 341 for details on command and data loading): 1. 1. a: load command ?0100 0000?. 2. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. 3. set bs2, bs1 to ?10?. this selects extended data byte. 4. 4. give w r a negative pulse and wait for rdy/bsy to go high. 5. 5. set bs2, bs1 to ?00?. this selects low data byte.
346 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-5. programming the fuses w aveforms 30.7.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 341 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is programmed (lb1 and lb2 is programmed), it is not possible to program the boot lock bits by any external programming mode. 3. give w r a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. 30.7.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 341 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, and bs2, bs1 to ?00?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, and bs2, bs1 to ?11?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, and bs2, bs1 to ?10?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, and bs2, bs1 to ?01?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. rdy/b s y wr oe re s et +12v pagel 0x40 data data xx xa1 xa0 b s 1 xtal1 ac 0x40 data xx ac write fuse low byte write fuse high byte 0x40 data xx ac write extended fuse byte b s 2
347 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-6. mapping between bs1, bs2 and the fuse and lock bits during read 30.7.13 reading the signature bytes the algorithm for reading the signatur e bytes is as follows (refer to ?programming the flash? on page 341 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 30.7.14 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to ?programming the flash? on page 341 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. 30.7.15 parallel programming characteristics figure 30-7. parallel programming timing, including some general timing requirements lock bits 0 1 b s 2 fuse high byte 0 1 b s 1 data fuse low byte 0 1 b s 2 extended fuse byte data & contol (data, xa0/1, b s 1, b s 2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/b s y pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl
348 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-8. parallel programming timing, loading sequence with timing requirements (1) n ote: 1. the timing requirements shown in figure 30-7 on page 347 (that is, t dvxh , t xhxl , and t xldx ) also apply to loading operation. figure 30-9. parallel programming timing, reading sequence (within the same page) with timing requirements (1) n ote: 1. the timing requirements shown in figure 30-7 on page 347 (that is, t dvxh , t xhxl , and t xldx ) also apply to reading operation. table 30-14. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 a xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data b s 1 xa0 xa1 load addre ss (low byte) load data (low byte) load data (high byte) load data load addre ss (low byte) xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data b s 1 xa0 xa1 load addre ss (low byte) read data (low byte) read data (high byte) load addre ss (low byte) t bvdv t oldv t xlol t ohdz
349 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. t w lrh is valid for the w rite flash, w rite eeprom, w rite fuse bits and w rite lock bits commands. 2. t w lrh_ce is valid for the chip erase command. 30.8 serial downloading both the flash and eeprom memo ry arrays can be programmed using a serial programming bus while reset is pulled to g n d. the serial programming interface consists of pins sck, pdi (input) and pdo (output). after reset is set low, the programming enable instruction needs to be executed first before program/erase operations can be executed. n ote, in table 30-15 on page 350 , the pin mapping for serial programming is listed. n ot all packages use the spi pins dedicated for the internal serial peripheral interface - spi. t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 t xhxl xtal1 pulse w idth high 150 t xldx data and control hold after xtal1 low 67 t xl w l xtal1 low to w r low 0 t xlph xtal1 low to pagel high 0 t plxh pagel low to xtal1 high 150 t bvph bs1 valid before pagel high 67 t phpl pag e l p u l s e w idth high 150 t plbx bs1 hold after pagel low 67 t w lbx bs2/1 hold after w r low 67 t pl w l pagel low to w r low 67 t bv w l bs2/1 valid to w r low 67 t w l w h w r pulse w idth low 150 t w lrl w r low to rdy/bsy low 0 1 s t w lrh w r low to rdy/bsy high (1) 3.7 4.5 ms t w lrh_ce w r low to rdy/bsy high for chip erase (2) 7.5 9 t xlol xtal1 low to oe low 0 ns t bvdv bs1 valid to data valid 0 250 t oldv oe low to data valid 250 t ohdz oe high to data tri-stated 250 table 30-14. parallel programming characteristics, v cc = 5v 10% (continued) symbol parameter min typ max units
350 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.8.1 serial programming pin mapping figure 30-10. serial programming and verify (1) n otes: 1. if the device is clocked by the internal oscilla tor, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < avcc < v cc + 0.3v, however, avcc should always be within 1.8v - 5.5v. w hen programming the eeprom, an auto-erase cycle is built into the self-timed programming oper- ation (in the serial mode o n ly) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck >= 12mhz high: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck >= 12mhz 30.8.2 serial programming algorithm w hen writing serial data to the atmega640/1280/1281/2560/2561, data is clocked on the rising edge of sck. w hen reading data from the atmega640/1280/1281/2560/2561, data is clocked on the falling edge of sck. see figure 30-12 on page 353 for timing details. to program and verify the atmega640/1280/1281/2560/2561 in the serial programming mode, the following sequence is recommended (see four byte instruction formats in table 30-17 on table 30-15. pin mapping serial programming symbol pins (tqfp-100) pins (tqfp-64) i/o description pdi pb2 pe0 i serial data in pdo pb3 pe1 o serial data out sck pb1 pb1 i serial clock vcc gnd xt al1 sck pdo pdi reset +1.8v - 5.5v avcc +1.8v - 5.5v (2)
351 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 page 352 ): 1. power-up sequence: apply power between v cc and g n d while reset and sck are set to ?0?. in some sys- tems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. w ait for at least 20ms and enable serial programming by sending the programming enable serial instruction to pin pdi. 3. the serial programming instructions will not wo rk if the communication is out of synchro- nization. w hen in sync. the second byte (0x53), w ill echo back when issuing the third byte of the programming enable instruction. w hether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 7 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the program memory page is stored by loading the w rite program memory page instruction with the address lines 15:8. before issuing this command, make sure the instruction load extended address byte has been used to define the msb of the address. the extended address byte is stored until the command is re-issued, that is, the command needs only be issued for the first page, and when crossing the 64k w ord boundary. if polling ( rdy/bsy ) is not used, the user must wait at least t w d_flash before issuing the next page (see table 30- 16 ). accessing the serial programming interface before the flash write operation com- pletes can result in incorrect programming. 5. the eeprom array is programmed one byte at a time by supplyin g the address and data together with the appropriate w rite instruction. an eeprom memory location is first automatically erased before new data is written. if polling is not used, the user must wait at least t w d_eeprom before issuing the next byte (see table 30-16 ). in a chip erased device, no 0xffs in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the con- tent at the selected address at serial output pdo. w hen reading the flash memory, use the instruction load extended address byte to define the upper address byte, which is not included in the read program memory instruction. the extended address byte is stored until the command is re-issued, that is, the command needs only be issued for the first page, and when crossing the 64k w ord boundary. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v cc power off. table 30-16. minimum w ait delay before w riting the n ext flash or eeprom location symbol minimum wait delay t w d_flash 4.5ms t w d_eeprom 3.6ms t w d_erase 9.0ms
352 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.8.3 serial programming instruction set table 30-17 and figure 30-11 on page 353 describes the instruction set. n otes: 1. n ot all instructions are applicable for all parts. 2. a = address. 3. bits are programmed ?0?, unprogrammed ?1?. 4. to ensure future compatibility, unused fuses and lock bits should be unprogrammed (?1?). 5. refer to the correspondig section for fuse and lock bits, calibration and signature bytes and page size. 6. see htt://www.atmel.com/avr for application n otes regarding programming and programmers. if the lsb in rdy/bsy data byte out is ?1?, a programming operation is still pending. w ait until this bit returns ?0? before the ne xt instruction is carried out. table 30-17. serial programming instruction set instruction/operation instruction format byte 1 byte 2 byte 3 byte 4 programming enable $ac $53 $00 $00 chip erase (program memory/eeprom) $ac $80 $00 $00 poll rdy/bsy $f0 $00 $00 data byte out load instructions load extended address byte (1) $4d $00 extended adr $00 load program memory page, high byte $48 $00 adr lsb high data byte in load program memory page, low byte $40 $00 adr lsb low data byte in load eeprom memory page (page access) $c1 $00 0000 000aa data byte in read instructions read program memory, high byte $28 adr msb adr lsb high data byte out read program memory, low byte $20 adr msb adr lsb low data byte out read eeprom memory $a0 0000 aaaa aaaa aaaa data byte out read lock bits $58 $00 $00 data byte out read signature byte $30 $00 0000 000aa data byte out read fuse bits $50 $00 $00 data byte out read fuse high bits $58 $08 $00 data byte out read extended fuse bits $50 $08 $00 data byte out read calibration byte $38 $00 $00 data byte out write instructions w rite program memory page $4c adr msb adr lsb $00 w rite eeprom memory $c0 0000 aaaa aaaa aaaa data byte in w rite eeprom memory page (page access) $c2 0000 aaaa aaaa 00 $00 w rite lock bits $ac $e0 $00 data byte in w rite fuse bits $ac $a0 $00 data byte in w rite fuse high bits $ac $a8 $00 data byte in w rite extended fuse bits $ac $a4 $00 data byte in
353 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 w ithin the same page, the low data byte must be loaded prior to the high data byte. after data is loaded to the page buffer, program the eeprom page, see figure 30-11 . figure 30-11. serial programming instruction example 30.8.4 serial programming characteristics for characteristics of the serial programming module, see ?spi timing characteristics? on page 375 . figure 30-12. serial programming w aveforms byte 1 byte 2 byte 3 byte 4 adr lsb bit 15 b 0 s erial programming instruction program memory/ eeprom memory page 0 page 1 page 2 page n-1 page buffer write program memory page/ write eeprom memory page load program memory page (high/low byte)/ load eeprom memory page (page access) byte 1 byte 2 byte 3 byte 4 bit 15 b 0 adr msb page offset page number ad r m m s s b a a adr r l l s b b m s b m s b l s b l s b s erial clock input ( s ck) s erial data input (mo s i) (mi s o) s ample s erial data output
354 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.9 programming via the jtag interface programming through the jtag interface requires control of the four jtag specific pins: tck, tms, tdi, and tdo. control of the reset and clock pins is not required. to be able to use the jtag interface, the jtage n fuse must be programmed. the device is default shipped with the fuse pr ogrammed. in addition, the jtd bit in mcucr must be cleared. alternatively, if the jtd bit is set, the external reset can be fo rced low. then, the jtd bit will be cleared after two chip clocks, and the jtag pins are available for programming. this provides a means of using the jtag pins as normal port pi ns in running mode while still allowing in-sys- tem programming via the jtag interface. n ote that this technique can not be used when using the jtag pins for boundary-scan or on-chip debug. in these cases the jtag pins must be ded- icated for this purpose. during programming the clock frequency of the tck input must be less than the maximum fre- quency of the chip. the system clock prescaler can not be used to divide the tck clock input into a sufficiently low frequency. as a definition in this datasheet, the lsb is shifted in and out first of all shift registers. 30.9.1 programming specific jtag instructions the instruction register is 4-bit wide, supporting up to 16 instructions. the jtag instructions useful for programming are listed below. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. the run-test/idle state of the tap controller is used to generate internal clocks. it can also be used as an idle state between jtag sequences . the state machine sequence for changing the instruction word is shown in figure 30-13 on page 355 .
355 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-13. state machine sequence for changing the instruction w ord 30.9.2 avr_reset (0xc) the avr specific public jtag in struction for setting the avr device in the reset mode or taking the device out from the reset mode. the tap controller is not reset by this instruction. the one bit reset register is selected as data register. n ote that the reset will be ac tive as long as there is a logic ?one? in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr : the reset register is shifted by the tck input 30.9.3 prog_enable (0x4) the avr specific public jtag instruction for enabling programming via the jtag port. the 16- bit programming enable register is selected as data register. the active states are the following: ? shift-dr : the programming enable signature is shifted into the data register ? update-dr : the programming enable signature is compared to the correct value, and programming mode is entered if the signature is valid test-logic-reset run-test/idle s hift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
356 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.9.4 prog_commands (0x5) the avr specific public jtag instruction for entering programming commands via the jtag port. the 15-bit programming command register is selected as data register. the active states are the following: ? capture-dr : the result of the previous command is loaded into the data register ? shift-dr : the data register is shifted by the tck input, shifting out the result of the previous command and shifting in the new command ? update-dr : the programming command is applied to the flash inputs ? run-test/idle : one clock cycle is generated, executing the applied command 30.9.5 prog_pageload (0x6) the avr specific public jtag instruction to directly load the flash data page via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? shift-dr : the flash data byte register is shifted by the tck input. ? update-dr : the content of the flash data byte register is copied into a temporary register. a write sequence is initiated that within 11 tck cycles loads the content of the temporary register into the flash page buffer. the avr automatically alternates between writing the low and the high byte for each new update-dr state, starting with the low byte for the first update-dr encountered after entering the prog_pageload command. the program counter is pre-incremented before writing the low byte, except fo r the first written byte. this ensures that the first data is written to the address set up by prog_comma n ds, and loading the last location in the page buffer does not make the program counter increment into the next page. 30.9.6 prog_pageread (0x7) the avr specific public jtag instruction to dire ctly capture the flash content via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? capture-dr : the content of the selected flash byte is captured into the flash data byte register. the avr automatically alternates between reading the low and the high byte for each new capture-dr state, starting with the low byte for the first capture-dr encountered after entering the prog_pageread command. the program counter is post-incremented after reading each high byte, including the first read byte. this ensures that the first data is captured from the first address set up by prog_comma n ds, and reading the last location in the page makes the program counter increment into the next page. ? shift-dr : the flash data byte register is shifted by the tck input. 30.9.7 data registers the data registers are selected by the jtag instruction registers described in section ?pro- gramming specific jtag instructions? on page 354 . the data registers relevant for programming operations are: ? reset register ? programming enable register ? programming command register ? flash data byte register
357 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.9.8 reset register the reset register is a test data register used to reset the part during programming. it is required to reset the part before entering programming mode. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high value present in t he reset register. depending on the fuse settings for the clock options, the part will remain reset for a re set time-out period (refer to ?clock sources? on page 41 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 28-2 on page 304 . 30.9.9 programming enable register the programming enable register is a 16-bit regist er. the contents of this register is compared to the programming enable signature, binary code 0b1010_0011_0111_0000. w hen the con- tents of the register is equal to the programming enable signature, programming via the jtag port is enabled. the register is reset to 0 on power-on reset, and should always be reset when leaving programming mode. figure 30-14. programming enable register 30.9.10 programming command register the programming command register is a 15-bit regist er. this register is us ed to serially shift in programming commands, and to serially shift out the result of the previous command, if any. the jtag programming instruction set is shown in table 30-18 on page 359 . the state sequence when shifting in the programmi ng commands is illustrated in figure 30-16 on page 362 . tdi tdo d a t a = dq clockdr & prog_enable programming enable 0xa370
358 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-15. programming command register tdi tdo s t r o b e s a d d r e s s / d a t a flash eeprom fuses lock bits
359 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 30-18. jtag programming instruction set a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes 1a. chip erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. poll for chip erase complete 0110011_10000000 xxxxx o x_xxxxxxxx (2) 2a. enter flash w rite 0100011_00010000 xxxxxxx_xxxxxxxx 2b. load address extended high byte 0001011_ cccccccc xxxxxxx_xxxxxxxx (10) 2c. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx 2d. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 2e. load data low byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 2f. load data high byte 0010111_ iiiiiiii xxxxxxx_xxxxxxxx 2g. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2h. w rite flash page 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2i. poll for page w rite complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 3a. enter flash read 0100011_00000010 xxxxxxx_xxxxxxxx 3b. load address extended high byte 0001011_ cccccccc xxxxxxx_xxxxxxxx (10) 3c. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx 3d. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 3e. read data low and high byte 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo low byte high byte 4a. enter eeprom w rite 0100011_00010001 xxxxxxx_xxxxxxxx 4b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (10) 4c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 4d. load data byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 4e. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4f. w rite eeprom page 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1)
360 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 4g. poll for page w rite complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 5a. enter eeprom read 0100011_00000011 xxxxxxx_xxxxxxxx 5b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (10) 5c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 5d. read data byte 0110011_ bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 6a. enter fuse w rite 0100011_01000000 xxxxxxx_xxxxxxxx 6b. load data low byte (6) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6c. w rite fuse extended byte 0111011_00000000 0111001_00000000 0111011_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6d. poll for fuse w rite complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6e. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6f. w rite fuse high byte 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6g. poll for fuse w rite complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6h. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6i. w rite fuse low byte 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6j. poll for fuse w rite complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 7a. enter lock bit w rite 0100011_00100000 xxxxxxx_xxxxxxxx 7b. load data byte (9) 0010011_11 iiiiii xxxxxxx_xxxxxxxx (4) 7c. w rite lock bits 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 7d. poll for lock bit w rite complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 8a. enter fuse/lock bit read 0100011_00000100 xxxxxxx_xxxxxxxx 8b. read extended fuse byte (6) 0111010_00000000 0111011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8c. read fuse high byte (7) 0111110_00000000 0111111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo table 30-18. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes
361 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this command sequence is not required if the seven msb are correctly set by the previous command sequence (which is normally the case). 2. repeat until o = ?1?. 3. set bits to ?0? to program the corresponding fuse, ?1? to unprogram the fuse. 4. set bits to ?0? to program the corresponding lock bit, ?1? to leave the lock bit unchanged. 5. ?0? = programmed, ?1? = unprogrammed. 6. the bit mapping for fuses extended byte is listed in table 30-3 on page 336 . 7. the bit mapping for fuses high byte is listed in table 30-4 on page 337 . 8. the bit mapping for fuses low byte is listed in table 30-5 on page 337 . 9. the bit mapping for lock bits byte is listed in table 30-1 on page 335 . 10. address bits exceeding pcmsb and eeamsb ( table 30-7 on page 338 and table 30-8 on page 338 ) are don?t care. 11. all tdi and tdo sequences are represented by binary digits (0b...). 8d. read fuse low byte (8) 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8e. read lock bits (9) 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xx oooooo (5) 8f. read fuses and lock bits 0111010_00000000 0111110_00000000 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo (5) fuse ext. byte fuse high byte fuse low byte lock bits 9a. enter signature byte read 0100011_00001000 xxxxxxx_xxxxxxxx 9b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 9c. read signature byte 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 10a. enter calibration byte read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 10c. read calibration byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 11a. load n o operation command 0100011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx table 30-18. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, c = address extended bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes
362 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 30-16. state machine sequence for changing/reading the data w ord 30.9.11 flash data byte register the flash data byte register provides an ef ficient way to load the entire flash page buffer before executing page w rite, or to read out/verify the content of the flash. a state machine sets up the control signals to the flash and senses the strobe signals from the flash, thus only the data words need to be shifted in/out. the flash data byte register actually consists of the 8-bit scan chain and a 8-bit temporary reg- ister. during page load, the update-dr state copies the content of the scan chain over to the temporary register and initiates a write sequence that within 11 tck cycles loads the content of the temporary register into the flash page bu ffer. the avr automatically alternates between writing the low and the high byte for each new update-dr state, starting with the low byte for the first update-dr encountered after entering the prog_pageload command. the program counter is pre-incremented before writing the low byte, except for the first written byte. this ensures that the first data is written to the address set up by prog_comma n ds, and loading the last location in the page buffer does not make the program counter increment into the next page. during page read, the content of the selected flash byte is captured into the flash data byte register during the capture-dr state. the avr automatically alternates between reading the low and the high byte for each new capture-dr state, starting with the low byte for the first cap- test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr s elect-ir s can capture-ir s hift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
363 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 ture-dr encountered after entering the prog_pageread command. the program counter is post-incremented after reading each high byte, including the first read byte. this ensures that the first data is captured from th e first address set up by prog_comma n ds, and reading the last location in the page makes the program counter increment into the next page. figure 30-17. flash data byte register the state machine controlling the flash data by te register is clocked by tck. during normal operation in which eight bits are shifted for eac h flash byte, the clock cycles needed to navigate through the tap controller automatically feeds the state machine for the flash data byte regis- ter with sufficient number of clock pulses to complete its operation transparently for the user. however, if too few bits are shifted between each update-dr state during page load, the tap controller should stay in the run-test/idle state for some tck cycles to ensure that there are at least 11 tck cycles between each update-dr state. 30.9.12 programming algorithm all references below of type ?1a?, ?1b?, and so on, refer to table 30-18 on page 359 . 30.9.13 entering programming mode 1. enter jtag instruction avr_reset and shift 1 in the reset register. 2. enter instruction prog_e n able and shift 0b1010_0011_0111_0000 in the program- ming enable register. 30.9.14 leaving programming mode 1. enter jtag instruction prog_comma n ds. 2. disable all programming instructions by using no operation instruction 11a. 3. enter instruction prog_e n able and shift 0b0000_0000_0000_0000 in the program- ming enable register. 4. enter jtag instruction avr_reset and shift 0 in the reset register. tdi tdo d a t a flash eeprom fuses lock bits s trobe s addre ss s tate machine
364 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 30.9.15 performing chip erase 1. enter jtag instruction prog_comma n ds. 2. start chip erase using pr ogramming instruction 1a. 3. poll for chip erase complete using programming instruction 1b, or wait for t w lrh_ce (refer to table 30-14 on page 348 ). 30.9.16 programming the flash before programming the flash a chip erase must be performed, see ?performing chip erase? on page 364. 1. enter jtag instruction prog_comma n ds. 2. enable flash write using programming instruction 2a. 3. load address extended high byte using programming instruction 2b. 4. load address high byte using programming instruction 2c. 5. load address low byte using programming instruction 2d. 6. load data using programming instructions 2e, 2f and 2g. 7. repeat steps 5 and 6 for all instruction words in the page. 8. w rite the page using programming instruction 2h. 9. poll for flash write complete using programming instruction 2i, or wait for t w lrh (refer to table 30-14 on page 348 ). 10. repeat steps 3 to 9 until all data have been programmed. a more efficient data transfer can be achieved using the prog_pageload instruction: 1. enter jtag instruction prog_comma n ds. 2. enable flash write using programming instruction 2a. 3. load the page address using programming instructions 2b, 2c and 2d. pc w ord (refer to table 30-7 on page 338 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageload. 5. load the entire page by shifting in all instruction words in the page byte-by-byte, starting with the lsb of the first instruction in the page and ending with the msb of the last instruction in the page. use update-dr to copy the contents of the flash data byte reg- ister into the flash page location and to auto-increment the program counter before each new word. 6. enter jtag instruction prog_comma n ds. 7. w rite the page using programming instruction 2h. 8. poll for flash write complete using programming instruction 2i, or wait for t w lrh (refer to table 30-14 on page 348 ). 9. repeat steps 3 to 8 until all data have been programmed. 30.9.17 reading the flash 1. enter jtag instruction prog_comma n ds. 2. enable flash read using programming instruction 3a. 3. load address using programming instructions 3b, 3c and 3d. 4. read data using programming instruction 3e. 5. repeat steps 3 and 4 until all data have been read.
365 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 a more efficient data transfer can be ac hieved using the prog_pageread instruction: 1. enter jtag instruction prog_comma n ds. 2. enable flash read using programming instruction 3a. 3. load the page address using programming instructions 3b, 3c and 3d. pc w ord (refer to table 30-7 on page 338 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageread. 5. read the entire page (or flash) by shifting out all instruction words in the page (or flash), starting with the lsb of the first instruction in the page (flash) and ending with the msb of the last instruction in the page (flash). the capture-dr state both captures the data from the flash, and also auto-increments the program counter after each word is read. n ote that capture-dr comes before the shift-dr state. hence, the first byte which is shifted out contains valid data. 6. enter jtag instruction prog_comma n ds. 7. repeat steps 3 to 6 until all data have been read. 30.9.18 programming the eeprom before programming the eeprom a chip erase must be performed, see ?performing chip erase? on page 364 . 1. enter jtag instruction prog_comma n ds. 2. enable eeprom write using programming instruction 4a. 3. load address high byte using programming instruction 4b. 4. load address low byte using programming instruction 4c. 5. load data using programming instructions 4d and 4e. 6. repeat steps 4 and 5 for all data bytes in the page. 7. w rite the data using programming instruction 4f. 8. poll for eeprom write complete using pr ogramming instruction 4g, or wait for t w lrh (refer to table 30-14 on page 348 ). 9. repeat steps 3 to 8 until all data have been programmed. n ote that the prog_pageload instruction ca n not be used when pr ogramming the eeprom. 30.9.19 reading the eeprom 1. enter jtag instruction prog_comma n ds. 2. enable eeprom read using programming instruction 5a. 3. load address using programming instructions 5b and 5c. 4. read data using programming instruction 5d. 5. repeat steps 3 and 4 until all data have been read. n ote that the prog_pageread instruction can not be used when reading the eeprom. 30.9.20 programming the fuses 1. enter jtag instruction prog_comma n ds. 2. enable fuse write using programming instruction 6a. 3. load data high byte using programming instru ctions 6b. a bit value of ?0? will program the corresponding fuse, a ?1? will unprogram the fuse. 4. w rite fuse high byte using programming instruction 6c.
366 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 5. poll for fuse write complete using prog ramming instruction 6d, or wait for t w lrh (refer to table 30-14 on page 348 ). 6. load data low byte using programming inst ructions 6e. a ?0? will pr ogram the fuse, a ?1? will unprogram the fuse. 7. w rite fuse low byte using programming instruction 6f. 8. poll for fuse write complete using prog ramming instruction 6g, or wait for t w lrh (refer to table 30-14 on page 348 ). 30.9.21 programming the lock bits 1. enter jtag instruction prog_comma n ds. 2. enable lock bit write using programming instruction 7a. 3. load data using prog ramming instructions 7b. a bit va lue of ?0? will program the corre- sponding lock bit, a ?1? will leave the lock bit unchanged. 4. w rite lock bits using programming instruction 7c. 5. poll for lock bit write complete using programming instruction 7d, or wait for t w lrh (refer to table 30-14 on page 348 ). 30.9.22 reading the fuses and lock bits 1. enter jtag instruction prog_comma n ds. 2. enable fuse/lock bit read using programming instruction 8a. 3. to read all fuses and lock bits, use programming instruction 8e. to only read fuse high byte, use programming instruction 8b. to only read fuse low byte, use programming instruction 8c. to only read lock bits, use programming instruction 8d. 30.9.23 reading the signature bytes 1. enter jtag instruction prog_comma n ds. 2. enable signature byte read using programming instruction 9a. 3. load address 0x00 using programming instruction 9b. 4. read first signature byte using programming instruction 9c. 5. repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third signature bytes, respectively. 30.9.24 reading the calibration byte 1. enter jtag instruction prog_comma n ds. 2. enable calibration byte read using programming instruction 10a. 3. load address 0x00 using programming instruction 10b. 4. read the calibration byte using programming instruction 10c.
367 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31. electrical characteristics absolute maximum ratings* 31.1 dc characteristics operating temperature.................................. -55 c to +125 c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of th is specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on any pin except reset with respect to ground ................................-0.5v to v cc +0.5v voltage on reset with respect to ground......-0.5v to +13.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ................................................ 40.0ma dc current v cc and g n d pins................................. 200.0ma t a = -40 c to 85 c, v cc = 1.8v to 5.5v (unless otherwise noted) symbol parameter condition min. typ. max. units v il input low voltage, except xtal1 and reset pin v cc = 1.8v - 2.4v v cc = 2.4v - 5.5v -0.5 -0.5 0.2v cc (1) 0.3v cc (1) v v il1 input low voltage, xtal1 pin v cc = 1.8v - 5.5v -0.5 0.1v cc (1) v il2 input low voltage, reset pin v cc = 1.8v - 5.5v -0.5 0.1v cc (1) v ih input high voltage, except xtal1 and reset pins v cc = 1.8v - 2.4v v cc = 2.4v - 5.5v 0.7v cc (2) 0.6v cc (2) v cc + 0.5 v cc + 0.5 v ih1 input high voltage, xtal1 pin v cc = 1.8v - 2.4v v cc = 2.4v - 5.5v 0.8v cc (2) 0.7v cc (2) v cc + 0.5 v cc + 0.5 v ih2 input high voltage, reset pin v cc = 1.8v - 5.5v 0.9v cc (2) v cc + 0.5 v ol output low voltage (3) , except reset pin i ol = 20ma, v cc = 5v i ol = 10ma, v cc = 3v 0.9 0.6 v oh output high voltage (4) , except reset pin i oh = -20ma, v cc = 5v i oh = -10ma, v cc = 3v 4.2 2.3 i il input leakage current i/o pin v cc = 5.5v, pin low (absolute value) 1 a i ih input leakage current i/o pin v cc = 5.5v, pin high (absolute value) 1 r rst reset pull-up resistor 30 60 k r pu i/o pin pull-up resistor 20 50
368 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. "max" means the highest value where the pin is guaranteed to be read as low. 2. "min" means the lowest value where the pin is guaranteed to be read as high. 3. although each i/o port can sink more than the test conditi ons (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), th e following must be observed: atmega1281/2561: 1.)the sum of all iol, for ports a0-a7, g2, c4-c7 should not exceed 100ma. 2.)the sum of all iol, for ports c0-c3, g0-g1, d0-d7 should not exceed 100ma. 3.)the sum of all iol, for ports g3-g5, b0-b7, e0-e7 should not exceed 100ma. 4.)the sum of all iol, for ports f0-f7 should not exceed 100ma. atmega640/1280/2560: 1.)the sum of all iol, for ports j0-j 7, a0-a7, g2 should not exceed 200ma. 2.)the sum of all iol, for ports c0-c7, g0 -g1, d0-d7, l0-l7 s hould not exceed 200ma. 3.)the sum of all iol, for ports g3-g4, b0-b7, h0-b7 should not exceed 200ma. 4.)the sum of all iol, for ports e0-e7, g5 should not exceed 100ma. 5.)the sum of all iol, for ports f0-f7, k0-k7 should not exceed 100ma. if iol exceeds the test condition, vol may exceed the related sp ecification. pins are not guar anteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test co nditions (20ma at vcc = 5v, 10ma at vcc = 3v) under steady state conditions (non-transient), the following must be observed: atmega1281/2561: 1)the sum of all ioh, for ports a0-a7, g2, c4-c7 should not exceed 100ma. 2)the sum of all ioh, for ports c0-c3, g0-g1, d0-d7 should not exceed 100ma. 3)the sum of all ioh, for ports g3-g5, b0-b7, e0-e7 should not exceed 100ma. 4)the sum of all ioh, for ports f0-f7 should not exceed 100ma. atmega640/1280/2560: 1)the sum of all ioh, for ports j0-j7, g2, a0-a7 should not exceed 200ma. 2)the sum of all ioh, for ports c0-c7, g0 -g1, d0-d7, l0-l7 should not exceed 200ma. 3)the sum of all ioh, for ports g3-g4, b0-b7, h0-h7 should not exceed 200ma. 4)the sum of all ioh, for ports e0-e7, g5 should not exceed 100ma. i cc power supply current (5) active 1mhz, v cc = 2v (atmega640/1280/2560/1v) 0.5 0.8 ma active 4mhz, v cc = 3v (atmega640/1280/2560/1l) 3.2 5 active 8mhz, v cc = 5v (atmega640/1280/1281/2560/2561) 10 14 idle 1mhz, v cc = 2v (atmega640/1280/2560/1v) 0.14 0.22 idle 4mhz, v cc = 3v (atmega640/1280/2560/1l) 0.7 1.1 idle 8mhz, v cc = 5v (atmega640/1280/1281/2560/2561) 2.7 4 power-down mode w dt enabled, v cc = 3v <5 15 a w dt disabled, v cc = 3v <1 7.5 v acio analog comparator input offset voltage v cc = 5v v in = v cc /2 <10 40 mv i aclk analog comparator input leakage current v cc = 5v v in = v cc /2 -50 50 na t acid analog comparator propagation delay v cc = 2.7v v cc = 4.0v 750 500 ns t a = -40 c to 85 c, v cc = 1.8v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min. typ. max. units
369 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 5)the sum of all ioh, for ports f0-f7, k0-k7 should not exceed 100ma. if ioh exceeds the test condition, voh ma y exceed the related specification. pins are not guaranteed to source current greater than the listed test condition. 5. values with ?prr1 ? power reduction register 1? enabled (0xff). 31.2 speed grades maximum frequency is depending on v cc. as shown in figure 31-1 trough figure 31-4 on page 370 , the maximum frequency vs. v cc curve is linear between 1.8v < v cc < 2.7v and between 2.7v < v cc < 4.5v. 31.2.1 8mhz figure 31-1. maximum frequency vs. v cc , atmega640v/1280v/1281v/2560v/2561v figure 31-2. maximum frequency vs. v cc when also n o-read- w hile- w rite section (1) , atmega2560v/atmega2561v, is used n ote: 1. w hen only using the read- w hile- w rite section of the program memory, a higher speed can be achieved at low voltage, see ?read- w hile- w rite and n o read- w hile- w rite flash sections? on page 317 for addresses. 8 mhz 4 mhz 1. 8 v 2.7v 5.5v s afe operating area 8 mhz 2 mhz 1. 8 v 2.7v 5.5v s afe operating area
370 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31.2.2 16 mhz figure 31-3. maximum frequency vs. v cc , atmega640/atmega1280/atmega1281 figure 31-4. maximum frequency vs. v cc , atmega2560/atmega2561 16 mhz 8 mhz 2.7v 4.5v 5.5v s afe operating area 16 mhz 4.5v 5.5v s afe operating area
371 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31.3 clock characteristics 31.3.1 calibrated internal rc oscillator accuracy n otes: 1. voltage range for atmega64 0v/1281v/1280v/2561v/2560v. 2. voltage range for atmega640/1281/1280/2561/2560. 31.3.2 external clock drive waveforms figure 31-5. external clock drive w aveforms 31.4 external clock drive table 31-1. calibration accuracy of internal rc oscillator frequency v cc temperature calibration accuracy factory calibration 8.0mhz 3v 25 c10% user calibration 7.3mhz - 8.1mhz 1.8v - 5.5v (1) 2.7v - 5.5v (2) -40 c - 85 c1% v il1 v ih1 table 31-2. external clock drive symbol parameter v cc = 1.8v - 5.5v v cc = 2.7v - 5.5v v cc = 4.5v - 5.5v units min. max. min. max. min. max. 1/t clcl oscillator frequency 0208016mhz t clcl clock period 500 125 62.5 ns t chcx high time 200 50 25 t clcx low time 200 50 25 t clch rise time 2.0 1.6 0.5 s t chcl fall time 2.0 1.6 0.5 t clcl change in period from one clock cycle to the next 22 2%
372 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31.5 system and reset characteristics n ote: 1. the power-on reset will not work un less the supply voltage has been below v pot (falling). 31.5.1 standard power-on reset this implementation of power-on reset existed in early versions of atmega640/1280/1281/2560/2561. the table below de scribes the characteristics of this power- on reset and it is valid for the following devices only: ? atmega640: revision a ? atmega1280: revision a ? atmega1281: revision a ? atmega2560: revision a to e ? atmega2561: revision a to e table 31-4. characteristics of standard power-on reset. t a = -40 to +85c. n otes: 1. values are guidelines only. 2. threshold where device is released from reset when voltage is rising. 3. the power-on reset threshold voltage (falling) will not work unless the supply voltage has been below v pot . table 31-3. reset, brown-out and internal voltage characteristicscharacteristics symbol parameter condi tion min typ max units v rst reset pin threshold voltage 0.2 v cc 0.9 v cc v t rst minimum pulse width on reset pin 2.5 s v hyst brown-out detector hysteresis 50 mv t bod min pulse w idth on brown-out reset 2 s v bg bandgap reference voltage v cc =2.7v, t a = 25 c 1.0 1.1 1.2 v t bg bandgap reference start-up time v cc =2.7v, t a = 25 c4070s i bg bandgap reference current consumption v cc =2.7v, t a = 25 c10 a symbol parameter min. (1) typ. (1) max. (1) units v pot power-on reset threshold voltage (rising) (2) 0.7 1.0 1.4 v power-on reset threshold voltage (falling) (3) 0.05 0.9 1.3 v v psr power-on slope rate 0.01 4.5 v/ms
373 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31.5.2 enhanced power-on reset this implementation of power-on reset exists in newer versions of atmega640/1280/1281/2560/2561. the table below de scribes the characteristics of this power- on reset and it is valid for the following devices only: ? atmega640: revision b and newer ? atmega1280: revision b and newer ? atmega1281: revision b and newer ? atmega2560: revision f and newer ? atmega2561: revision f and newer table 31-5. characteristics of enhanced power-on reset. t a = -40 to +85c. n otes: 1. values are guidelines only. 2. threshold where device is released from reset when voltage is rising. 3. the power-on reset threshold voltage (falling) will not work unless the supply voltage has been below v pot . n ote: 1. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, the device is tested down to v cc = v bot during the production test. this guarantees that a brown-out reset will occur before v cc drops to a voltage where correct operation of the microcontroller is no longer guaran teed. the test is performed using bodlevel = 110 for 4mhz operation of atmega640v/1280v/ 1281v/2560v/2561v, bodlevel = 101 for 8mhz operation of atmega640v/1280v/1281v/2560v/2561v and atmega640/1280/1281, and bodlevel = 100 for 16mhz operation of atmega640/1280/1281/2560/2561. 31.6 2-wire serial inte rface characteristics table 31-7 on page 374 describes the requirements for devices connected to the 2-wire serial bus. the atmega640/1280/1281/2560/2561 2-wire serial interface meets or exceeds these requirements under the noted conditions. timing symbols refer to figure 31-6 on page 375 . symbol parameter min. (1) typ. (1) max. (1) units v pot power-on reset threshold voltage (rising) (2) 1.1 1.4 1.6 v power-on reset threshold voltage (falling) (3) 0.6 1.3 1.6 v v psr power-on slope rate 0.01 v/ms table 31-6. bodlevel fuse coding (1) bodlevel 2:0 fuses min v bot typ v bot max v bot units 111 bod disabled 110 1.7 1.8 2.0 v 101 2.5 2.7 2.9 100 4.1 4.3 4.5 011 reserved 010 001 000
374 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. in atmega640/1280/1281/2560/2561, this para meter is characterized and not 100% tested. 2. required only for f scl > 100khz. 3. c b = capacitance of one bus line in pf. 4. f ck = cpu clock frequency. table 31-7. 2-wire serial bus requirements symbol parameter condition min max units v il input low-voltage -0.5 0.3 v cc v v ih input high-voltage 0.7 v cc v cc + 0.5 v hys (1) hysteresis of schmitt trigger inputs 0.05 v cc (2) ? v ol (1) output low-voltage 3ma sink current 0 0.4 t r (1) rise time for both sda and scl 20 + 0.1c b (3)(2) 300 ns t of (1) output fall time from v ihmin to v ilmax 10pf < c b < 400pf (3) 20 + 0.1c b (3)(2) 250 t sp (1) spikes suppressed by input filter 0 50 (2) i i input current each i/o pin 0.1v cc < v i < 0.9v cc -10 10 a c i (1) capacitance for each i/o pin ? 10 pf f scl scl clock frequency f ck (4) > max(16f scl , 250khz) (5) 0 400 khz rp value of pull-up resistor f scl 100khz f scl > 100khz t hd;sta hold time (repeated) start condition f scl 100khz 4.0 ? s f scl > 100khz 0.6 ? t lo w low period of the scl clock f scl 100khz (6) 4.7 ? f scl > 100khz (7) 1.3 ? t high high period of the scl clock f scl 100khz 4.0 ? f scl > 100khz 0.6 ? t su;sta set-up time for a repeated start condition f scl 100khz 4.7 ? f scl > 100khz 0.6 ? t hd;dat data hold time f scl 100khz 0 3.45 f scl > 100khz 0 0.9 t su;dat data setup time f scl 100khz 250 ? f scl > 100khz 100 ? t su;sto setup time for stop condition f scl 100khz 4.0 ? f scl > 100khz 0.6 ? t buf bus free time between a stop and start condition f scl 100khz 4.7 ? f scl > 100khz 1.3 ? v cc 0.4v ? 3ma ---------------------------- 1000ns c b ------------------- v cc 0.4v ? 3ma ---------------------------- 300 ns c b ----------------- -
375 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 5. this requirement applies to all atme ga640/1280/1281/2560/2561 2-wire serial interface operation. other devices con- nected to the 2-wire serial bus need only obey the general f scl requirement. 6. the actual low period generated by the atmega640/ 1280/1281/2560/2561 2-wire serial interface is (1/f scl - 2/f ck ), thus f ck must be greater than 6mhz for the low time requirement to be strictly met at f scl = 100khz. 7. the actual low period generated by the atmega640/1280/1281/2560/2561 2-wire serial interface is (1/f scl - 2/f ck ), thus the low time requirement will not be strictly met for f scl > 308khz when f ck = 8mhz. still, atmega640/1280/1281/2560/2561 devices connected to the bus may communicate at fu ll speed (400khz) with other atmega640/1280/1281/2560/2561 devices, as well as any other device with a proper t lo w acceptance margin. figure 31-6. 2-wire serial bus timing 31.7 spi timing characteristics see figure 31-7 on page 376 and figure 31-8 on page 376 for details. n ote: 1. in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12mhz - 3 t clcl for f ck > 12mhz t su;sta t low t high t low t of t hd;sta t hd;dat t su;dat t su;sto t buf scl sda t r table 31-8. spi timing parameters description mode min typ max 1 sck period master see table 21-5 on page 203 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master 3.6 4 setup master 10 5hold master 10 6 out to sck master 0.5 ? t sck 7 sck to out master 10 8 sck to out high master 10 9ss low to out slave 15 10 sck period slave 4 ? t ck 11 sck high/low (1) slave 2 ? t ck 12 rise/fall time slave 1600 13 setup slave 10 14 hold slave t ck 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 20
376 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 31-7. spi interface timing requirements (master mode) figure 31-8. spi interface timing requirements (slave mode) mo s i (data output) s ck (cpol = 1) mi s o (data input) s ck (cpol = 0) ss m s bl s b l s b m s b ... ... 61 22 3 45 8 7 mi so (data output) s ck (cpol = 1) mo si (data input) s ck (cpol = 0) ss m s bl s b l s b m s b ... ... 10 11 11 12 13 14 17 15 9 x 16
377 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 31.8 adc characteristics ? preliminary data n ote: 1. values are guidelines only. table 31-9. adc characteristics, singel ended channels symbol parameter condition min (1) typ (1) max (1) units resolution single ended conversion 10 bits absolute accuracy (including i n l, d n l, quantization error, gain and offset error) single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz 2.25 2.5 lsb single ended conversion v ref = 4v, v cc = 4v, clk adc = 1mhz 3 single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz n oise reduction mode 2 single ended conversion v ref = 4v, v cc = 4v, clk adc = 1mhz n oise reduction mode 3 integral n on-linearity (i n l) single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz 1.25 differential n on-linearity (d n l) single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz 0.5 gain error single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz 2 offset error single ended conversion v ref = 4v, v cc = 4v, clk adc = 200khz -2 conversion time free running conversion 13 260 s clock frequency single ended conversion 50 1000 khz avcc analog supply voltage v cc - 0.3 v cc + 0.3 v v ref reference voltage 1.0 avcc v i n input voltage g n dv ref input bandwidth 38,5 khz v i n t1 internal voltage reference 1.1v 1.0 1.1 1.2 v v i n t2 internal voltage reference 2.56v 2.4 2.56 2.8 r ref reference input resistance 32 k r ai n analog input resistance 100 m
378 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 31-10. adc characteristics, differential channels symbol parameter condition min (1) typ (1) max (1) units resolution gain = 1 8 bits gain = 10 8 gain = 200 7 absolute accuracy(including i n l, d n l, quantization error, gain and offset error) gain = 1 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 18 lsb gain = 10 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 17 gain = 200 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 9 integral n on-linearity (i n l) gain = 1 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 2.5 gain = 10 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 5 gain = 200 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 9 differential n on-linearity (d n l) gain = 1 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 0.75 gain = 10 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 1.5 gain = 200 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 10 gain error gain = 1 1.7 % gain = 10 1.7 gain = 200 0.5 offset error gain = 1 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 2 lsb gain = 10 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 2 gain = 200 v ref = 4v, v cc = 5v clk adc = 50 - 200khz 3 clock frequency 50 200 khz conversion time 65 260 s
379 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: values are guidelines only. 31.9 external data memory timing n otes: 1. this assumes 50% clock duty cycle. the half period is actually the high time of the external clock, xtal1. 2. this assumes 50% clock duty cycle. the half period is actually the low time of the external clock, xtal1. avcc analog supply voltage v cc - 0.3 v cc + 0.3 v v ref reference voltage 2.7 avcc - 0.5 v i n input voltage g n dv cc v diff input differential voltage -v ref /gain v ref /gain adc conversion output -511 511 lsb input bandwidth 4khz v i n t internal voltage reference 2.3 2.56 2.8 v r ref reference input resistance 32 k r ai n analog input resistance 100 m table 31-11. external data memory characteristics, 4.5 to 5.5 volts, n o w ait-state symbol parameter 8mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 1t lhll ale pulse w idth 115 1.0t clcl -10 ns 2t avll address valid a to ale low 57.5 0.5t clcl -5 (1) 3a t llax_st address hold after ale low, write access 55 3b t llax_ld address hold after ale low, read access 55 4t avllc address valid c to ale low 57.5 0.5t clcl -5 (1) 5t avrl address valid to rd low 115 1.0t clcl -10 6t av w l address valid to w r low 115 1.0t clcl -10 7t ll w l ale low to w r low 47.5 67.5 0.5t clcl -15 (2) 0.5t clcl +5 (2) 8t llrl ale low to rd low 47.5 67.5 0.5t clcl -15 (2) 0.5t clcl +5 (2) 9t dvrh data setup to rd high 40 40 10 t rldv read low to data valid 75 1.0t clcl -50 11 t rhdx data hold after rd high 0 0 12 t rlrh rd pulse w idth 115 1.0t clcl -10 13 t dv w l data setup to w r low 42.5 0.5t clcl -20 (1) 14 t w hdx data hold after w r high 115 1.0t clcl -10 15 t dv w h data valid to w r high 125 1.0t clcl 16 t w l w h w r pulse w idth 115 1.0t clcl -10 table 31-10. adc characteristics, differe ntial channels (continued) symbol parameter condition min (1) typ (1) max (1) units
380 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table 31-12. external data memory characterist ics, 4.5 to 5.5 volts, 1 cycle w ait-state symbol parameter 8mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 200 2.0t clcl -50 ns 12 t rlrh rd pulse w idth 240 2.0t clcl -10 15 t dv w h data valid to w r high 240 2.0t clcl 16 t w l w h w r pulse w idth 240 2.0t clcl -10 table 31-13. external data memory characteristics, 4.5 to 5.5 volts, sr w n1 = 1, sr w n0 = 0 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 325 3.0t clcl -50 ns 12 t rlrh rd pulse w idth 365 3.0t clcl -10 15 t dv w h data valid to w r high 375 3.0t clcl 16 t w l w h w r pulse w idth 365 3.0t clcl -10 table 31-14. external data memory characteristics, 4.5 to 5.5 volts, sr w n1 = 1, sr w n0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 16 mhz 10 t rldv read low to data valid 325 3.0t clcl -50 ns 12 t rlrh rd pulse w idth 365 3.0t clcl -10 14 t w hdx data hold after w r high 240 2.0t clcl -10 15 t dv w h data valid to w r high 375 3.0t clcl 16 t w l w h w r pulse w idth 365 3.0t clcl -10 table 31-15. external data memory characteristics, 2.7 to 5.5 volts, n o w ait-state symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz
381 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this assumes 50% clock duty cycle. the half period is actually the high time of the external clock, xtal1. 2. this assumes 50% clock duty cycle. the half period is actually the low time of the external clock, xtal1. 1t lhll ale pulse w idth 235 t clcl -15 ns 2t avll address valid a to ale low 115 0.5t clcl -10 (1) 3a t llax_st address hold after ale low, write access 55 3b t llax_ld address hold after ale low, read access 55 4t avllc address valid c to ale low 115 0.5t clcl -10 (1) 5t avrl address valid to rd low 235 1.0t clcl -15 6t av w l address valid to w r low 235 1.0t clcl -15 7t ll w l ale low to w r low 115 130 0.5t clcl -10 (2) 0.5t clcl +5 (2) 8t llrl ale low to rd low 115 130 0.5t clcl -10 (2) 0.5t clcl +5 (2) 9t dvrh data setup to rd high 45 45 10 t rldv read low to data valid 190 1.0t clcl -60 11 t rhdx data hold after rd high 0 0 12 t rlrh rd pulse w idth 235 1.0t clcl -15 13 t dv w l data setup to w r low 105 0.5t clcl -20 (1) 14 t w hdx data hold after w r high 235 1.0t clcl -15 15 t dv w h data valid to w r high 250 1.0t clcl 16 t w l w h w r pulse w idth 235 1.0t clcl -15 table 31-15. external data memory characteristics, 2.7 to 5.5 volts, n o w ait-state (continued) symbol parameter 4mhz oscillator variable oscillator unit min max min max table 31-16. external data memory characteristics, 2.7 to 5.5 volts, sr w n1 = 0, sr w n0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 440 2.0t clcl -60 ns 12 t rlrh rd pulse w idth 485 2.0t clcl -15 15 t dv w h data valid to w r high 500 2.0t clcl 16 t w l w h w r pulse w idth 485 2.0t clcl -15
382 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 31-9. external memory timing (sr w n1 = 0, sr w n0 = 0 table 31-17. external data memory characteristics, 2.7 to 5.5 volts, sr w n1 = 1, sr w n0 = 0 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 690 3.0t clcl -60 ns 12 t rlrh rd pulse w idth 735 3.0t clcl -15 15 t dv w h data valid to w r high 750 3.0t clcl 16 t w l w h w r pulse w idth 735 3.0t clcl -15 table 31-18. external data memory characteristics, 2.7 to 5.5 volts, sr w n1 = 1, sr w n0 = 1 symbol parameter 4mhz oscillator variable oscillator unit min max min max 01/t clcl oscillator frequency 0.0 8 mhz 10 t rldv read low to data valid 690 3.0t clcl -60 ns 12 t rlrh rd pulse w idth 735 3.0t clcl -15 14 t w hdx data hold after w r high 485 2.0t clcl -15 15 t dv w h data valid to w r high 750 3.0t clcl 16 t w l w h w r pulse w idth 735 3.0t clcl -15 ale t1 t2 t3 write read wr t4 a15: 8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address s ystem clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9
383 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 31-10. external memory timing (sr w n1 = 0, sr w n0 = 1) figure 31-11. external memory timing (sr w n1 = 1, sr w n0 = 0) ale t1 t2 t3 write read wr t5 a15: 8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address s ystem clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 ale t1 t2 t3 write read wr t6 a15: 8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address s ystem clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 t5
384 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 31-12. external memory timing (sr w n1 = 1, sr w n0 = 1) () the ale pulse in the last period (t 4-t7) is only present if the next instruction accesses the ram (internal or external). ale t1 t2 t3 write read wr t7 a15: 8 address prev. addr. da7:0 address data prev. data xx rd da7:0 (xmbk = 0) data address s ystem clock (clk cpu ) 1 4 2 7 6 3a 3b 5 8 12 16 13 10 11 14 15 9 t4 t5 t6
385 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32. typical characteristics the following charts show typical behavior. t hese figures are not tested during manufacturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail-to-rail output is used as clock source. all active- and idle current consumption measurem ents are done with all bits in the prr regis- ters set and thus, the corresponding i/o modules are turned off. also the analog comparator is disabled during these measurements. table 32-1 on page 390 and table 32-2 on page 391 show the additional current consumption compared to i cc active and i cc idle for every i/o mod- ule controlled by the power reduction register. see ?power reduction register? on page 54 for details. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient tempera- ture. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pi ns may be estimated (for one pin) as c l v cc f where c l = load capacitance, v cc = operating voltage and f = average switching frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaranteed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with w atchdog timer enabled and power-down mode with w atchdog timer disabled represents the differential cur- rent drawn by the w atchdog timer. 32.1 active supply current figure 32-1. active supply current vs. frequency (0.1mhz - 1.0mhz) 5.5v 5.0v 4.5v 4.0v 3.3v 2.7v 1. 8 v 0 0.5 1 1.5 2 2.5 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 fr eq u en cy (mhz) i cc (m a )
386 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-2. active supply current vs . frequency (1mhz - 16mhz) figure 32-3. active supply current vs. v cc (internal rc o scillator, 8mhz) 5.5v 5.0v 4.5v 0 5 10 15 20 25 0246 8 10 12 14 16 fr eq u en cy (mhz) i cc (m a) 4.0v 3.3v 2.7v 1. 8 v 8 5c 25c -40c 0 2 4 6 8 10 12 14 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
387 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-4. active supply current vs. v cc (internal rc o scillator, 1mhz) figure 32-5. active supply current vs. v cc (internal rc o scillator, 128khz) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 8 5c 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
388 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.2 idle supply current figure 32-6. idle supply current vs. low frequency (0.1mhz - 1.0mhz) figure 32-7. idle supply current vs. frequency (1mhz - 16mhz) 5.5v 5.0v 4.5v 4.0v 3.3v 2.7v 1. 8 v 0 0.1 0.2 0.3 0.4 0.5 0.6 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fr eq u en cy (mhz) i cc (ma) 5.5v 5.0v 4.5v 0 1 2 3 4 5 6 7 8 0246 8 10 12 14 16 fr eq u en cy (mhz) i cc (m a) 4.0v 3.3v 2.7v 1. 8 v
389 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-8. idle supply current vs. v cc (internal rc o scillator, 8mhz) figure 32-9. idle supply current vs. v cc (internal rc o scillator, 1mhz) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 3 3.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 8 5c 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
390 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-10. idle supply current vs. v cc (internal rc o scillator, 128khz)i 32.2.1 supply current of io modules the tables and formulas below can be used to calculate the additional current consumption for the different i/o modules in active and idle mode. the enabling or disabling of the i/o modules are controlled by the power reduction register. see ?power reduction register? on page 54 for details. 8 5c 25c -40c 0 0.05 0.1 0.15 0.2 0.25 0.3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (m a ) table 32-1. additional current consumption for the different i/o modules (absolute values) prr bit typical numbers v cc = 2v, f = 1mhz v cc = 3v, f = 4mhz v cc = 5v, f = 8mhz prusart3 8.0a 51a 220a prusart2 8.0a 51a 220a prusart1 8.0a 51a 220a prusart0 8.0a 51a 220a prt w i 12a 75a 315a prtim5 6.0a 39a 150a prtim4 6.0a 39a 150a prtim3 6.0a 39a 150a prtim2 11a 72a 300a prtim1 6.0a 39a 150a prtim0 4.0a 24a 100a prspi 15a 95a 400a pradc 12a 75a 315a
391 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 it is possible to calculate the typical current consumption based on the numbers from table 32-1 on page 390 for other v cc and frequency settings than listed in table 32-2 . 32.2.1.1 example 1 calculate the expected current consumption in idle mode with usart0, timer1, and t w i enabled at v cc = 2.0v and f = 1mhz. from table 32-2 , third column, we see that we need to add 17% for the usart0, 24% for the t w i, and 10% for the timer1 module. reading from fig- ure 32-6 on page 388 , we find that the idle current consumption is ~0.15ma at v cc = 2.0v and f = 1mhz. the total current consumption in idle mode with usart0, timer1, and t w i enabled, gives: table 32-2. additional current consumption (percentage) in active and idle mode prr bit additional current consumption compared to active wi th external clock additional current consumption compared to idle with external clock prusart3 3.0% 17% prusart2 3.0% 17% prusart1 3.0% 17% prusart0 3.0% 17% prt w i4.4% 24% prtim5 1.8% 10% prtim4 1.8% 10% prtim3 1.8% 10% prtim2 4.3% 23% prtim1 1.8% 10% prtim0 1.5% 8.0% prspi 3.3% 18% pradc 4.5% 24% i cc total 0.15 ma 10.170.240.10 +++ () ? 0.227 ma ?
392 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.3 power-down supply current figure 32-11. power-down supply current vs. v cc ( w atchdog timer disabled) figure 32-12. power-down supply current vs. v cc ( w atchdog timer enabled) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 3 3.5 4 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a ) 25c -40c 0 2 4 6 8 10 12 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a) 8 5c
393 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.4 power-save supply current figure 32-13. power-save supply current vs. v cc ( w atchdog timer disabled) figure 32-14. power-save supply current vs. v cc ( w atchdog timer enabled) 25c 4 5 6 7 8 9 10 11 1.5 2 2.5 33 .5 4 4.5 5 5.5 v cc (v) i cc ( a) 0 1 2 3 4 5 6 7 8 9 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a) 25c
394 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.5 standby supply current figure 32-15. standby supply current vs. v cc ( w atchdog timer disabled) 32.6 pin pull-up figure 32-16. i/o pin pull-up resistor current vs. input voltage (v cc = 1.8v) 6mhz xtal 6mhz res 4mhz xtal 4mhz res 455khz res 32khz xtal 2mhz xtal 2mhz res 1mhz res 0 0.02 0.04 0.06 0.0 8 0.1 0.12 0.14 0.16 0.1 8 0.2 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (m a ) 8 5c 25c -40c 0 10 20 30 40 50 60 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 1.6 1. 8 2 v op (v) i op (a )
395 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-17. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7v) figure 32-18. i/o pin pull-up resistor current vs. input voltage (v cc = 5v) 8 5c 25c -40c 0 10 20 30 40 50 60 70 8 0 90 0 0.5 1 1.5 2 2.5 3 v op (v) i op (a) 8 5c 25c -40c 0 20 40 60 8 0 100 120 140 160 0123456 v op (v) i op (a )
396 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-19. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 1.8v) figure 32-20. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 2.7v) 8 5c 25c -40c 0 5 10 15 20 25 30 35 40 0 0.2 0.4 0.6 0. 8 1 1.2 1.4 1.6 1. 8 2 v re s et (v) i re s et (a) 8 5c 25c -40c 0 10 20 30 40 50 60 70 0 0.5 1 1.5 2 2.5 3 v re s et (v) i re s et (a)
397 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-21. reset pull-up resistor curr ent vs. reset pin voltage (v cc = 5v) 32.7 pin driver strength figure 32-22. i/o pin output voltage vs.sink current (v cc = 3v) 8 5c 25c -40c 0 20 40 60 8 0 100 120 0123 456 v re s et (v) i re s et (a) 8 5c 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 0 5 10 15 20 25 i ol (ma) v ol (v )
398 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-23. i/o pin output voltage vs. sink current (v cc = 5v) figure 32-24. i/o pin output voltage vs. source current (v cc = 3v) 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0 5 10 15 20 25 i ol (ma) v ol (v) 8 5c 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 3 3.5 0 5 10 15 20 25 i oh (ma) v oh (v)
399 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-25. i/o pin output voltage vs. source current (v cc = 5v) 32.8 pin threshold and hysteresis figure 32-26. i/o pin input threshold voltage vs. v cc (v ih , io pin read as ?1?) 8 5c 25c -40c 4.3 4.4 4.5 4.6 4.7 4. 8 4.9 5 5.1 0 5 10 15 20 25 i oh (ma) v oh (v) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 3 3.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) th r esh o l d (v)
400 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-27. i/o pin input threshold voltage vs. v cc (v il , io pin read as ?0?) figure 32-28. i/o pin input hysteresis 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) th r esh o l d (v) 8 5c 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i nput hyst eres is (mv)
401 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-29. reset input threshold voltage vs. v cc (v ih , io pin read as ?1?) figure 32-30. reset input threshold voltage vs. v cc (v il , io pin read as ?0?) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) th r es hold (v ) 8 5c 25c -40c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) th r esh o l d (v)
402 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-31. reset pin input hysteresis vs. v cc 32.9 bod threshold and analog comparator offset figure 32-32. bod threshold vs. temperature (bod level is 4.3v) 8 5c 25c -40c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) input hy steresis (mv) rising vcc falling vcc 4.2 4.25 4.3 4.35 4.4 -60 -40 -20 0 20 40 60 80 100 temperature (c) threshold (v)
403 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-33. bod threshold vs. temperature (bod level is 2.7v) figure 32-34. bod threshold vs. temperature (bod level is 1.8v) rising vcc falling vcc 2.6 2.65 2.7 2.75 2.8 -60 -40 -20 0 20 40 60 80 100 temperature (c) threshold (v) rising vcc fallling vcc 1.7 1.75 1.8 1.85 1.9 -60 -40 -20 0 20 40 60 80 100 temperature (c) t hre shold ( v )
404 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.10 internal oscillator speed figure 32-35. w atchdog oscillator frequency vs. v cc figure 32-36. w atchdog oscillator freq uency vs. temperature 8 5c 25c -40c 114 116 11 8 120 122 124 126 12 8 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (khz) 5.5v 4.0v 3.3v 2.7v 2.1v 114 116 11 8 120 122 124 126 12 8 -60 -40 -20 0 20 40 60 8 0 100 temperat ure (c) f rc (khz )
405 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-37. calibrated 8mhz rc oscillator frequency vs. v cc figure 32-38. calibrated 8mhz rc oscillator frequency vs. temperature 8 5c 25c -40c 7.6 7.7 7. 8 7.9 8 8 .1 8 .2 8 .3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) 5.0v 3.0v 7.9 8 8 .1 8 .2 8 .3 8 .4 8 .5 -60 -40 -20 0 20 40 60 8 0 100 temperat ure (c) f rc (mhz)
406 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-39. calibrated 8mhz rc oscillator frequency vs. osccal value 32.11 current consumption of peripheral units figure 32-40. brownout detector current vs. v cc 8 5c 25c -40c 0 2 4 6 8 10 12 14 16 016324 8 64 8 0 96 112 12 8 144 160 176 192 20 8 224 240 256 o s ccal (x1) f rc (mhz) 8 5c 25c -40c 0 5 10 15 20 25 30 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a)
407 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-41. adc current vs. v cc (aref = av cc ) figure 32-42. aref external reference current vs. v cc 8 5c 25c -40c 0 50 100 150 200 250 300 350 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a) 8 5c 25c -40c 0 50 100 150 200 250 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a)
408 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-43. w atchdog timer current vs. v cc figure 32-44. analog comparator current vs. v cc 8 5c 25c -40c 0 1 2 3 4 5 6 7 8 9 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a) 8 5c 25c -40c 0 10 20 30 40 50 60 70 8 0 90 100 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (a )
409 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-45. programming current vs. v cc 32.12 current consumption in reset and reset pulsewidth figure 32-46. reset supply current vs v cc (0.1mhz - 1.0mhz, excluding current through the reset pull-up) 8 5c 25c -40c 0 2 4 6 8 10 12 14 16 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 5.5v 5.0v 4.5v 4.0v 3.3v 2.7v 1. 8 v 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0. 8 0.9 1 fr eq u en cy (mhz) i cc (m a )
410 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 figure 32-47. reset supply current vs. v cc (1mhz - 16mhz, excluding current through the reset pull-up) figure 32-48. minimum reset pulse w idth vs. v cc 5.5v 5.0v 4.5v 0 0.5 1 1.5 2 2.5 3 3.5 4 0246 8 10 12 14 16 fr eq u en cy (mhz) i cc (m a) 4.0v 3.3v 2.7v 1. 8 v 8 5c 25c -40c 0 500 1000 1500 2000 2500 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) pu l se w i d t h (ns)
411 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 33. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0x1ff) reserved - - - - - - - - ... reserved - - - - - - - - (0x13f) reserved (0x13e) reserved (0x13d) reserved (0x13c) reserved (0x13b) reserved (0x13a) reserved (0x139) reserved (0x138) reserved (0x137) reserved (0x136) udr3 usart3 i/o data register 222 (0x135) ubrr3h - - - - usart3 baud rate register high byte 227 (0x134) ubrr3l usart3 baud rate register low byte 227 (0x133) reserved - - - - - - - - (0x132) ucsr3c umsel31 umsel30 upm 31 upm30 usbs3 ucsz31 ucsz30 ucpol3 239 (0x131) ucsr3b rxcie3 txcie3 udrie3 rxe n 3txe n 3 ucsz32 rxb83 txb83 238 (0x130) ucsr3a rxc3 txc3 udre3 fe3 dor3 upe3 u2x3 mpcm3 238 (0x12f) reserved - - - - - - - - (0x12e) reserved - - - - - - - - (0x12d) ocr5ch timer/counter5 - output compare register c high byte 165 (0x12c) ocr5cl timer/counter5 - output compare register c low byte 165 (0x12b) ocr5bh timer/counter5 - output compare register b high byte 165 (0x12a) ocr5bl timer/counter5 - output compare register b low byte 165 (0x129) ocr5ah timer/counter5 - output compare register a high byte 164 (0x128) ocr5al timer/counter5 - output compare register a low byte 164 (0x127) icr5h timer/counter5 - input capture register high byte 165 (0x126) icr5l timer/counter5 - input capture register low byte 165 (0x125) tc n t5h timer/counter5 - counter register high byte 163 (0x124) tc n t5l timer/counter5 - counter register low byte 163 (0x123) reserved - - - - - - - - (0x122) tccr5c foc5a foc5b foc5c - - - - - 162 (0x121) tccr5b ic n c5 ices5 - w gm53 w gm52 cs52 cs51 cs50 160 (0x120) tccr5a com5a1 com5a0 com5b1 com5b0 com5c1 com5c0 w gm51 w gm50 158 (0x11f) reserved - - - - - - - - (0x11e) reserved - - - - - - - - (0x11d) reserved - - - - - - - - (0x11c) reserved - - - - - - - - (0x11b) reserved - - - - - - - - (0x11a) reserved - - - - - - - - (0x119) reserved - - - - - - - - (0x118) reserved - - - - - - - - (0x117) reserved - - - - - - - - (0x116) reserved - - - - - - - - (0x115) reserved - - - - - - - - (0x114) reserved - - - - - - - - (0x113) reserved - - - - - - - - (0x112) reserved - - - - - - - - (0x111) reserved - - - - - - - - (0x110) reserved - - - - - - - - (0x10f) reserved - - - - - - - - (0x10e) reserved - - - - - - - - (0x10d) reserved - - - - - - - - (0x10c) reserved - - - - - - - - (0x10b) portl portl7 portl6 portl5 portl4 portl3 portl2 portl1 portl0 104 (0x10a) ddrl ddl7 ddl6 ddl5 ddl4 ddl3 ddl2 ddl1 ddl0 104 (0x109) pi n lpi n l7 pi n l6 pi n l5 pi n l4 pi n l3 pi n l2 pi n l1 pi n l0 104 (0x108) portk portk7 portk6 portk5 portk4 portk3 portk2 portk1 portk0 103 (0x107) ddrk ddk7 ddk6 ddk5 ddk4 ddk3 ddk2 ddk1 ddk0 103 (0x106) pi n kpi n k7 pi n k6 pi n k5 pi n k4 pi n k3 pi n k2 pi n k1 pi n k0 103 (0x105) portj portj7 portj6 portj5 portj4 portj3 portj2 portj1 portj0 103 (0x104) ddrj ddj7 ddj6 ddj5 ddj4 ddj3 ddj2 ddj1 ddj0 103 (0x103) pi n jpi n j7 pi n j6 pi n j5 pi n j4 pi n j3 pi n j2 pi n j1 pi n j0 103 (0x102) porth porth7 porth6 porth5 porth4 porth3 porth2 porth1 porth0 102 (0x101) ddrh ddh7 ddh6 ddh5 ddh4 ddh3 ddh2 ddh1 ddh0 103
412 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 (0x100) pi n hpi n h7 pi n h6 pi n h5 pi n h4 pi n h3 pi n h2 pi n h1 pi n h0 103 (0xff) reserved - - - - - - - - (0xfe) reserved - - - - - - - - (0xfd) reserved - - - - - - - - (0xfc) reserved - - - - - - - - (0xfb) reserved - - - - - - - - (0xfa) reserved - - - - - - - - (0xf9) reserved - - - - - - - - (0xf8) reserved - - - - - - - - (0xf7) reserved - - - - - - - - (0xf6) reserved - - - - - - - - (0xf5) reserved - - - - - - - - (0xf4) reserved - - - - - - - - (0xf3) reserved - - - - - - - - (0xf2) reserved - - - - - - - - (0xf1) reserved - - - - - - - - (0xf0) reserved - - - - - - - - (0xef) reserved - - - - - - - - (0xee) reserved - - - - - - - - (0xed) reserved - - - - - - - - (0xec) reserved - - - - - - - - (0xeb) reserved - - - - - - - (0xea) reserved - - - - - - - - (0xe9) reserved - - - - - - - - (0xe8) reserved - - - - - - - - (0xe7) reserved - - - - - - - (0xe6) reserved - - - - - - - - (0xe5) reserved - - - - - - - - (0xe4) reserved - - - - - - - - (0xe3) reserved - - - - - - - (0xe2) reserved - - - - - - - - (0xe1) reserved - - - - - - - (0xe0) reserved - - - - - - - (0xdf) reserved - - - - - - - - (0xde) reserved - - - - - - - - (0xdd) reserved - - - - - - - (0xdc) reserved - - - - - - - - (0xdb) reserved - - - - - - - - (0xda) reserved - - - - - - - - (0xd9) reserved - - - - - - - (0xd8) reserved - - - - - - - - (0xd7) reserved - - - - - - - - (0xd6) udr2 usart2 i/o data register 222 (0xd5) ubrr2h - - - - usart2 baud rate register high byte 227 (0xd4) ubrr2l usart2 baud rate register low byte 227 (0xd3) reserved - - - - - - - - (0xd2) ucsr2c umsel21 umsel20 upm2 1 upm20 usbs2 ucsz21 ucsz20 ucpol2 239 (0xd1) ucsr2b rxcie2 txcie2 udrie2 rxe n 2txe n 2 ucsz22 rxb82 txb82 238 (0xd0) ucsr2a rxc2 txc2 udre2 fe2 dor2 upe2 u2x2 mpcm2 238 (0xcf) reserved - - - - - - - - (0xce) udr1 usart1 i/o data register 222 (0xcd) ubrr1h - - - - usart1 baud rate register high byte 227 (0xcc) ubrr1l usart1 baud rate register low byte 227 (0xcb) reserved - - - - - - - - (0xca) ucsr1c umsel11 umsel10 upm1 1 upm10 usbs1 ucsz11 ucsz10 ucpol1 239 (0xc9) ucsr1b rxcie1 txcie1 udrie1 rxe n 1txe n 1 ucsz12 rxb81 txb81 238 (0xc8) ucsr1a rxc1 txc1 udre1 fe1 dor1 upe1 u2x1 mpcm1 238 (0xc7) reserved - - - - - - - - (0xc6) udr0 usart0 i/o data register 222 (0xc5) ubrr0h - - - - usart0 baud rate register high byte 227 (0xc4) ubrr0l usart0 baud rate register low byte 227 (0xc3) reserved - - - - - - - - (0xc2) ucsr0c umsel01 umsel00 upm0 1 upm00 usbs0 ucsz01 ucsz00 ucpol0 239 (0xc1) ucsr0b rxcie0 txcie0 udrie0 rxe n 0txe n 0 ucsz02 rxb80 txb80 238 (0xc0) ucsr0a rxc0 txc0 udre0 fe0 dor0 upe0 u2x0 mpcm0 238 (0xbf) reserved - - - - - - - - address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
413 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 (0xbe) reserved - - - - - - - - (0xbd) t w amr t w am6 t w am5 t w am4 t w am3 t w am2 t w am1 t w am0 - 269 (0xbc) t w cr t w i n tt w ea t w sta t w sto t ww ct w e n -t w ie 266 (0xbb) t w dr 2-wire serial interface data register 268 (0xba) t w ar t w a6 t w a5 t w a4 t w a3 t w a2 t w a1 t w a0 t w gce 269 (0xb9) t w sr t w s7 t w s6 t w s5 t w s4 t w s3 -t w ps1 t w ps0 268 (0xb8) t w br 2-wire serial interface bit rate register 266 (0xb7) reserved - - - - - - - - (0xb6) assr -exclkas2tc n 2ub ocr2aub ocr2bub tcr2aub tcr2bub 184 (0xb5) reserved - - - - - - - - (0xb4) ocr2b timer/counter2 output compare register b 191 (0xb3) ocr2a timer/counter2 output compare register a 191 (0xb2) tc n t2 timer/counter2 (8 bit) 191 (0xb1) tccr2b foc2a foc2b - - w gm22 cs22 cs21 cs20 190 (0xb0) tccr2a com2a1 com2a0 com2b1 com2b0 - - w gm21 w gm20 191 (0xaf) reserved - - - - - - - - (0xae) reserved - - - - - - - - (0xad) ocr4ch timer/counter4 - output compare register c high byte 164 (0xac) ocr4cl timer/counter4 - output compare register c low byte 164 (0xab) ocr4bh timer/counter4 - output compare register b high byte 164 (0xaa) ocr4bl timer/counter4 - output compare register b low byte 164 (0xa9) ocr4ah timer/counter4 - output compare register a high byte 164 (0xa8) ocr4al timer/counter4 - output compare register a low byte 164 (0xa7) icr4h timer/counter4 - input capture register high byte 165 (0xa6) icr4l timer/counter4 - input capture register low byte 165 (0xa5) tc n t4h timer/counter4 - counter register high byte 163 (0xa4) tc n t4l timer/counter4 - counter register low byte 163 (0xa3) reserved - - - - - - - - (0xa2) tccr4c foc4a foc4b foc4c - - - - - 162 (0xa1) tccr4b ic n c4 ices4 - w gm43 w gm42 cs42 cs41 cs40 160 (0xa0) tccr4a com4a1 com4a0 com4b1 com4b0 com4c1 com4c0 w gm41 w gm40 158 (0x9f) reserved - - - - - - - - (0x9e) reserved - - - - - - - - (0x9d) ocr3ch timer/counter3 - output compare register c high byte 164 (0x9c) ocr3cl timer/counter3 - output compare register c low byte 164 (0x9b) ocr3bh timer/counter3 - output compare register b high byte 164 (0x9a) ocr3bl timer/counter3 - output compare register b low byte 164 (0x99) ocr3ah timer/counter3 - output compare register a high byte 163 (0x98) ocr3al timer/counter3 - output compare register a low byte 163 (0x97) icr3h timer/counter3 - input capture register high byte 165 (0x96) icr3l timer/counter3 - input capture register low byte 165 (0x95) tc n t3h timer/counter3 - counter register high byte 162 (0x94) tc n t3l timer/counter3 - counter register low byte 162 (0x93) reserved - - - - - - - - (0x92) tccr3c foc3a foc3b foc3c - - - - - 162 (0x91) tccr3b ic n c3 ices3 - w gm33 w gm32 cs32 cs31 cs30 160 (0x90) tccr3a com3a1 com3a0 com3b1 com3b0 com3c1 com3c0 w gm31 w gm30 158 (0x8f) reserved - - - - - - - - (0x8e) reserved - - - - - - - - (0x8d) ocr1ch timer/counter1 - output compare register c high byte 163 (0x8c) ocr1cl timer/counter1 - output compare register c low byte 163 (0x8b) ocr1bh timer/counter1 - output compare register b high byte 163 (0x8a) ocr1bl timer/counter1 - output compare register b low byte 163 (0x89) ocr1ah timer/counter1 - output compare register a high byte 163 (0x88) ocr1al timer/counter1 - output compare register a low byte 163 (0x87) icr1h timer/counter1 - input capture register high byte 165 (0x86) icr1l timer/counter1 - input capture register low byte 165 (0x85) tc n t1h timer/counter1 - counter register high byte 162 (0x84) tc n t1l timer/counter1 - counter register low byte 162 (0x83) reserved - - - - - - - - (0x82) tccr1c foc1a foc1b foc1c - - - - - 161 (0x81) tccr1b ic n c1 ices1 - w gm13 w gm12 cs12 cs11 cs10 160 (0x80) tccr1a com1a1 com1a0 com1b1 com1b0 com1c1 com1c0 w gm11 w gm10 158 (0x7f) didr1 - - - - - -ai n 1d ai n 0d 274 (0x7e) didr0 adc7d adc6d adc5d adc4d adc3d adc2d adc1d adc0d 295 (0x7d) didr2 adc15d adc14d adc13d adc12d adc11d adc10d adc9d adc8d 295 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
414 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 (0x7c) admux refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 289 (0x7b) adcsrb -acme - - mux5 adts2 adts1 adts0 272 , 290 , 294 (0x7a) adcsra ade n adsc adate adif adie adps2 adps1 adps0 292 (0x79) adch adc data register high byte 294 (0x78) adcl adc data register low byte 294 (0x77) reserved - - - - - - - - (0x76) reserved - - - - - - - - (0x75) xmcrb xmbk - - - - xmm2 xmm1 xmm0 38 (0x74) xmcra sre srl2 srl1 srl0 sr w 11 sr w 10 sr w 01 sr w 00 37 (0x73) timsk5 - -icie5 - ocie5c ocie5b ocie5a toie5 166 (0x72) timsk4 - -icie4 - ocie4c ocie4b ocie4a toie4 166 (0x71) timsk3 - -icie3 - ocie3c ocie3b ocie3a toie3 166 (0x70) timsk2 - - - - - ocie2b ocie2a toie2 193 (0x6f) timsk1 - -icie1 - ocie1c ocie1b ocie1a toie1 166 (0x6e) timsk0 - - - - - ocie0b ocie0a toie0 134 (0x6d) pcmsk2 pci n t23 pci n t22 pci n t21 pci n t20 pci n t19 pci n t18 pci n t17 pci n t16 116 (0x6c) pcmsk1 pci n t15 pci n t14 pci n t13 pci n t12 pci n t11 pci n t10 pci n t9 pci n t8 116 (0x6b) pcmsk0 pci n t7 pci n t6 pci n t5 pci n t4 pci n t3 pci n t2 pci n t1 pci n t0 117 (0x6a) eicrb isc71 isc70 isc61 isc60 isc51 isc50 isc41 isc40 114 (0x69) eicra isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 113 (0x68) pcicr - - - - - pcie2 pcie1 pcie0 115 (0x67) reserved - - - - - - - - (0x66) osccal oscillator calibration register 50 (0x65) prr1 - - prtim5 prtim4 prtim3 prusart3 prusart2 prusart1 57 (0x64) prr0 prt w i prtim2 prtim0 - prtim1 prspi prusart0 pradc 56 (0x63) reserved - - - - - - - - (0x62) reserved - - - - - - - - (0x61) clkpr clkpce - - - clkps3 clkps2 clkps1 clkps0 50 (0x60) w dtcsr w dif w die w dp3 w dce w de w dp2 w dp1 w dp0 67 0x3f (0x5f) sreg i t h s v n zc 14 0x3e (0x5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 16 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 16 0x3c (0x5c) ei n d - - - - - - -ei n d0 17 0x3b (0x5b) rampz - - - - - - rampz1 rampz0 17 0x3a (0x5a) reserved - - - - - - - - 0x39 (0x59) reserved - - - - - - - - 0x38 (0x58) reserved - - - - - - - - 0x37 (0x57) spmcsr spmie r ww sb sigrd r ww sre blbset pg w rt pgers spme n 332 0x36 (0x56) reserved - - - - - - - - 0x35 (0x55) mcucr jtd - -pud - - ivsel ivce 67 , 110 , 100 , 308 0x34 (0x54) mcusr - - -jtrf w drf borf extrf porf 308 0x33 (0x53) smcr - - - - sm2 sm1 sm0 se 52 0x32 (0x52) reserved - - - - - - - - 0x31 (0x51) ocdr ocdr7 ocdr6 ocdr5 ocdr4 ocdr3 ocdr2 ocdr1 ocdr0 301 0x30 (0x50) acsr acd acbg aco aci acie acic acis1 acis0 272 0x2f (0x4f) reserved - - - - - - - - 0x2e (0x4e) spdr spi data register 204 0x2d (0x4d) spsr spif w col - - - - - spi2x 203 0x2c (0x4c) spcr spie spe dord mstr cpol cpha spr1 spr0 202 0x2b (0x4b) gpior2 general purpose i/o register 2 37 0x2a (0x4a) gpior1 general purpose i/o register 1 37 0x29 (0x49) reserved - - - - - - - - 0x28 (0x48) ocr0b timer/counter0 output compare register b 133 0x27 (0x47) ocr0a timer/counter0 output compare register a 133 0x26 (0x46) tc n t0 timer/counter0 (8 bit) 133 0x25 (0x45) tccr0b foc0a foc0b - - w gm02 cs02 cs01 cs00 132 0x24 (0x44) tccr0a com0a1 com0a0 com0b1 com0b0 - - w gm01 w gm00 129 0x23 (0x43) gtccr tsm - - - - - psrasy psrsy n c 170 , 194 0x22 (0x42) eearh - - - - eeprom address register high byte 35 0x21 (0x41) eearl eeprom address register low byte 35 0x20 (0x40) eedr eeprom data register 35 0x1f (0x3f) eecr - - eepm1 eepm0 eerie eempe eepe eere 35 0x1e (0x3e) gpior0 general purpose i/o register 0 37 0x1d (0x3d) eimsk i n t7 i n t6 i n t5 i n t4 i n t3 i n t2 i n t1 i n t0 115 0x1c (0x3c) eifr i n tf7 i n tf6 i n tf5 i n tf4 i n tf3 i n tf2 i n tf1 i n tf0 115 0x1b (0x3b) pcifr - - - - - pcif2 pcif1 pcif0 116 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
415 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. for compatibility with future devices, reserved bits s hould be written to zero if accessed. reserved i/o memory addresse s should never be written. 2. i/o registers within the address range $00 - $1f are directly bit-accessible using th e sbi and cbi instructions. in these reg - isters, the value of single bits can be checked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. n ote that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag r ead as set, thus clearing the fl ag. the cbi and sbi instruction s work with registers 0x00 to 0x1f only. 4. w hen using the i/o specific commands i n and out, the i/o addresses $00 - $3f must be used. w hen addressing i/o regis- ters as data space using ld and st instructions, $20 must be added to these addresses. the atmega640/1280/1281/2560/2561 is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the i n and out instructions. for the extended i/o space from $60 - $1ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. 0x1a (0x3a) tifr5 - -icf5 - ocf5c ocf5b ocf5a tov5 166 0x19 (0x39) tifr4 - -icf4 - ocf4c ocf4b ocf4a tov4 167 0x18 (0x38) tifr3 - -icf3 - ocf3c ocf3b ocf3a tov3 167 0x17 (0x37) tifr2 - - - - - ocf2b ocf2a tov2 193 0x16 (0x36) tifr1 - -icf1 - ocf1c ocf1b ocf1a tov1 167 0x15 (0x35) tifr0 - - - - - ocf0b ocf0a tov0 134 0x14 (0x34) portg - - portg5 portg4 portg3 portg2 portg1 portg0 102 0x13 (0x33) ddrg - - ddg5 ddg4 ddg3 ddg2 ddg1 ddg0 102 0x12 (0x32) pi n g - -pi n g5 pi n g4 pi n g3 pi n g2 pi n g1 pi n g0 102 0x11 (0x31) portf portf7 portf6 portf5 portf4 portf3 portf2 portf1 portf0 101 0x10 (0x30) ddrf ddf7 ddf6 ddf5 ddf4 ddf3 ddf2 ddf1 ddf0 102 0x0f (0x2f) pi n fpi n f7 pi n f6 pi n f5 pi n f4 pi n f3 pi n f2 pi n f1 pi n f0 102 0x0e (0x2e) porte porte7 porte6 porte 5 porte4 porte3 porte2 porte1 porte0 101 0x0d (0x2d) ddre dde7 dde6 dde5 dde4 dde3 dde2 dde1 dde0 101 0x0c (0x2c) pi n epi n e7 pi n e6 pi n e5 pi n e4 pi n e3 pi n e2 pi n e1 pi n e0 102 0x0b (0x2b) portd portd7 portd6 portd 5 portd4 portd3 portd2 portd1 portd0 101 0x0a (0x2a) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 101 0x09 (0x29) pi n dpi n d7 pi n d6 pi n d5 pi n d4 pi n d3 pi n d2 pi n d1 pi n d0 101 0x08 (0x28) portc portc7 portc6 portc5 portc4 portc3 portc2 portc1 portc0 101 0x07 (0x27) ddrc ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 101 0x06 (0x26) pi n cpi n c7 pi n c6 pi n c5 pi n c4 pi n c3 pi n c2 pi n c1 pi n c0 101 0x05 (0x25) portb portb7 portb6 portb 5 portb4 portb3 portb2 portb1 portb0 100 0x04 (0x24) ddrb ddb7 ddb6 d db5 ddb4 ddb3 ddb2 ddb1 ddb0 100 0x03 (0x23) pi n bpi n b7 pi n b6 pi n b5 pi n b4 pi n b3 pi n b2 pi n b1 pi n b0 100 0x02 (0x22) porta porta7 porta6 porta 5 porta4 porta3 porta2 porta1 porta0 100 0x01 (0x21) ddra dda7 dda6 d da5 dda4 dda3 dda2 dda1 dda0 100 0x00 (0x20) pi n api n a7 pi n a6 pi n a5 pi n a4 pi n a3 pi n a2 pi n a1 pi n a0 100 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
416 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 34. instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z, c, n , v, h 1 adc rd, rr add with carry two registers rd rd + rr + c z, c, n , v, h 1 adi w rdl,k add immediate to w ord rdh:rdl rdh:rdl + k z, c, n , v, s 2 sub rd, rr subtract two registers rd rd - rr z, c, n , v, h 1 subi rd, k subtract constant from register rd rd - k z, c, n , v, h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z, c, n , v, h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z, c, n , v, h 1 sbi w rdl,k subtract immediate from w ord rdh:rdl rdh:rdl - k z, c, n , v, s 2 a n d rd, rr logical a n d registers rd rd ? rr z, n , v 1 a n di rd, k logical a n d register and constant rd rd ? kz, n , v 1 or rd, rr logical or registers rd rd v rr z, n , v 1 ori rd, k logical or register and constant rd rd v k z, n , v 1 eor rd, rr exclusive or registers rd rd rr z, n , v 1 com rd one?s complement rd 0xff ? rd z, c, n , v 1 n eg rd two?s complement rd 0x00 ? rd z, c, n , v, h 1 sbr rd,k set bit(s) in register rd rd v k z, n , v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z, n , v 1 i n c rd increment rd rd + 1 z, n , v 1 dec rd decrement rd rd ? 1 z, n , v 1 tst rd test for zero or minus rd rd ? rd z, n , v 1 clr rd clear register rd rd rd z, n , v 1 ser rd set register rd 0xff n one 1 mul rd, rr multiply unsigned r1:r0 rd x rr z, c 2 muls rd, rr multiply signed r1:r0 rd x rr z, c 2 mulsu rd, rr multiply signed with unsigned r1:r0 rd x rr z, c 2 fmul rd, rr fractional multiply unsigned r1:r0 (rd x rr) << 1 z, c 2 fmuls rd, rr fractional multiply signed r1:r0 (rd x rr) << 1 z, c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 (rd x rr) << 1 z, c 2 branch instructions rjmp k relative jump pc pc + k + 1 n one 2 ijmp indirect jump to (z) pc z n one 2 eijmp extended indirect jump to (z) pc (ei n d:z) n one 2 jmp k direct jump pc k n one 3 rcall k relative subroutine call pc pc + k + 1 n one 4 icall indirect call to (z) pc z n one 4 eicall extended indirect call to (z) pc (ei n d:z) n one 4 call k direct subroutine call pc k n one 5 ret subroutine return pc stack n one 5 reti interrupt return pc stack i 5 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 n one 1/2/3 cp rd,rr compare rd ? rr z, n , v, c, h 1 cpc rd,rr compare with carry rd ? rr ? c z, n , v, c, h 1 cpi rd,k compare register with immediate rd ? k z, n , v, c, h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 n one 1/2/3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc pc + 2 or 3 n one 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 n one 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 n one 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 n one 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 n one 1/2 breq k branch if equal if (z = 1) then pc pc + k + 1 n one 1/2 br n e k branch if n ot equal if (z = 0) then pc pc + k + 1 n one 1/2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 n one 1/2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 n one 1/2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 n one 1/2 brlo k branch if lower if (c = 1) then pc pc + k + 1 n one 1/2 brmi k branch if minus if ( n = 1) then pc pc + k + 1 n one 1/2 brpl k branch if plus if ( n = 0) then pc pc + k + 1 n one 1/2 brge k branch if greater or equal, signed if ( n v= 0) then pc pc + k + 1 n one 1/2 brlt k branch if less than zero, signed if ( n v= 1) then pc pc + k + 1 n one 1/2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 n one 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 n one 1/2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 n one 1/2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 n one 1/2
417 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 n one 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 n one 1/2 brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 n one 1/2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 n one 1/2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) 1 n one 2 cbi p,b clear bit in i/o register i/o(p,b) 0 n one 2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z, c, n , v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z, c, n , v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z, c, n , v 1 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z, c, n , v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0..6 z, c, n , v 1 s w ap rd swap n ibbles rd(3..0) rd(7..4),rd(7..4) rd(3..0) n one 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) t n one 1 sec set carry c 1c1 clc clear carry c 0 c 1 se n set n egative flag n 1 n 1 cl n clear n egative flag n 0 n 1 sez set zero flag z 1z1 clz clear ze ro flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 sev set twos complement overflow. v 1v1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1t1 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1h1 clh clear half carry flag in sreg h 0 h 1 data transfer instructions mov rd, rr move between registers rd rr n one 1 mov w rd, rr copy register w ord rd+1:rd rr+1:rr n one 1 ldi rd, k load immediate rd k n one 1 ld rd, x load indirect rd (x) n one 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 n one 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) n one 2 ld rd, y load indirect rd (y) n one 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 n one 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) n one 2 ldd rd,y+q load indirect with displacement rd (y + q) n one 2 ld rd, z load indirect rd (z) n one 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 n one 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) n one 2 ldd rd, z+q load indirect with displacement rd (z + q) n one 2 lds rd, k load direct from sram rd (k) n one 2 st x, rr store indirect (x) rr n one 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 n one 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr n one 2 st y, rr store indirect (y) rr n one 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 n one 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr n one 2 std y+q,rr store indirect with displacement (y + q) rr n one 2 st z, rr store indirect (z) rr n one 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 n one 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr n one 2 std z+q,rr store indirect with displacement (z + q) rr n one 2 sts k, rr store direct to sram (k) rr n one 2 lpm load program memory r0 (z) n one 3 lpm rd, z load program memory rd (z) n one 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 n one 3 elpm extended load program memory r0 (rampz:z) n one 3 elpm rd, z extended load program memory rd (rampz:z) n one 3 mnemonics operands description operation flags #clocks
418 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n ote: eicall and eijmp do not exist in atmega640/1280/1281. elpm does not exist in atmega640. elpm rd, z+ extended load program memory rd (rampz:z), rampz:z rampz:z+1 n one 3 spm store program memory (z) r1:r0 n one - i n rd, p in port rd p n one 1 out p, rr out port p rr n one 1 push rr push register on stack stack rr n one 2 pop rd pop register from stack rd stack n one 2 mcu control instructions n op n o operation n one 1 sleep sleep (see specific descr. for sleep function) n one 1 w dr w atchdog reset (see specific descr. for w dr/timer) n one 1 break break for on-chip debug only n one n /a mnemonics operands description operation flags #clocks
419 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 35. ordering information n otes: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. see ?speed grades? on page 369. 3. pb-free packaging, complies to the european directive for restriction of hazardous subst ances (rohs directive). also halide free and fully green. 4. tape & reel. 35.1 atmega640 speed (mhz) (2) power supply ordering code package (1)(3) operation range 8 1.8 - 5.5v atmega640v-8au atmega640v-8aur (4) atmega640v-8cu atmega640v-8cur (4) 100a 100a 100c1 100c1 industrial (-40 c to 85 c) 16 2.7 - 5.5v atmega640-16au atmega640-16aur (4) atmega640-16cu atmega640-16cur (4) 100a 100a 100c1 100c1 package type 100a 100-lead, thin (1.0mm) plastic gull w ing quad flat package (tqfp) 100c1 100-ball, chip ball grid array (cbga)
420 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. see ?speed grades? on page 369 . 3. pb-free packaging, complies to the european directive for restriction of hazardous subst ances (rohs directive). also halide free and fully green. 4. tape & reel. 35.2 atmega1280 speed (mhz) (2) power supply ordering code package (1)(3) operation range 8 1.8v - 5.5v atmega1280v-8au atmega1280v-8aur (4) atmega1280v-8cu atmega1280v-8cur (4) 100a 100a 100c1 100c1 industrial (-40 c to 85 c) 16 2.7v - 5.5v atmega1280-16au atmega1280-16aur (4) atmega1280-16cu atmega1280-16cur (4) 100a 100a 100c1 100c1 package type 100a 100-lead, thin (1.0mm) plastic gull w ing quad flat package (tqfp) 100c1 100-ball, chip ball grid array (cbga)
421 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. see ?speed grades? on page 369 . 3. pb-free packaging, complies to the european directive for restriction of hazardous subst ances (rohs directive). also halide free and fully green. 4. tape & reel. 35.3 atmega1281 speed (mhz) (2) power supply ordering code package (1)(3) operation range 8 1.8 - 5.5v atmega1281v-8au atmega1281v-8aur (4) atmega1281v-8mu atmega1281v-8mur (4) 64a 64a 64m2 64m2 industrial (-40 c to 85 c) 16 2.7 - 5.5v atmega1281-16au atmega1281-16aur (4) atmega1281-16mu atmega1281-16mur (4) 64a 64a 64m2 64m2 package type 64a 64-lead, thin (1.0mm) plastic gull w ing quad flat package (tqfp) 64m2 64-pad, 9mm 9mm 1.0mm body, quad flat n o-lead/micro lead frame package (qf n /mlf)
422 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. see ?speed grades? on page 369 . 3. pb-free packaging, complies to the european directive for restriction of hazardous subst ances (rohs directive). also halide free and fully green. 4. tape & reel. 35.4 atmega2560 speed (mhz) (2) power supply ordering code package (1)(3) operation range 8 1.8v - 5.5v atmega2560v-8au atmega2560v-8aur (4) atmega2560v-8cu atmega2560v-8cur (4) 100a 100a 100c1 100c1 industrial (-40 c to 85 c) 16 4.5v - 5.5v atmega2560-16au atmega2560-16aur (4) atmega2560-16cu atmega2560-16cur (4) 100a 100a 100c1 100c1 package type 100a 100-lead, thin (1.0mm) plastic gull w ing quad flat package (tqfp) 100c1 100-ball, chip ball grid array (cbga)
423 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 n otes: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. see ?speed grades? on page 369 . 3. pb-free packaging, complies to the european directive for restriction of hazardous subst ances (rohs directive). also halide free and fully green. 4. tape & reel. 35.5 atmega2561 speed (mhz) (2) power supply ordering code package (1)(3) operation range 81.8v - 5.5v atmega1281v-8au atmega1281v-8aur (4) atmega1281v-8mu atmega1281v-8mur (4) 64a 64a 64m2 64m2 industrial (-40 c to 85 c) 16 4.5v - 5.5v atmega1281-16au atmega1281-16aur (4) atmega1281-16mu atmega1281-16mur (4) 64a 64a 64m2 64m2 package type 64a 64-lead, thin (1.0mm) plastic gull w ing quad flat package (tqfp) 64m2 64-pad, 9mm 9mm 1.0mm body, quad flat n o-lead/micro lead frame package (qf n /mlf)
424 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 36. packaging information 36.1 100a 2 3 25 orch a rd p a rkw a y s a n jo s e, ca 951 3 1 title drawing no. r rev. 100a, 100-le a d, 14 x 14mm body size, 1.0mm body thickne ss , 0.5mm le a d pitch, thin profile pl as tic q ua d fl a t p a ck a ge (tqfp) d 100a 2010-10-20 pin 1 identifier 0~7 pin 1 l c a1 a2 a d1 d e e1 e b a ? ? 1.20 a1 0.05 ? 0.15 a2 0.95 1.00 1.05 d 15.75 16.00 16.25 d1 1 3 .90 14.00 14.10 note 2 e 15.75 16.00 16.25 e1 1 3 .90 14.00 14.10 note 2 b 0.17 ? 0.27 c 0.09 ? 0.20 l 0.45 ? 0.75 e 0.50 typ note s : 1. thi s p a ck a ge conform s to jedec reference ms-026, v a ri a tion aed. 2. dimen s ion s d1 a nd e1 do not incl u de mold protr us ion. allow ab le protr us ion i s 0.25mm per s ide. dimen s ion s d1 a nd e1 a re m a xim u m pl as tic b ody s ize dimen s ion s incl u ding mold mi s m a tch. 3 . le a d copl a n a rity i s 0.08mm m a xim u m. common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note
425 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 36.2 100c1 2325 orchard parkway san jose, ca 95131 title drawing no. r rev. 100c1 , 100-ball, 9 x 9 x 1.2 mm body, ball pitch 0.80 mm chip array bga package (cbga) a 100c1 5/25/06 top view side view bottom view common dimensions (unit of measure = mm) symbol min nom max note a 1.10 ? 1.20 a1 0.30 0.35 0.40 d 8.90 9.00 9.10 e 8.90 9.00 9.10 d1 7.10 7.20 7.30 e1 7.10 7.20 7.30 ? b 0.35 0.40 0.45 e 0.80 typ marked a1 identifier 1 2 3 4 5 6 7 8 a b c d e 9 f g h i j 10 0.90 typ 0.90 typ a1 corner 0.12 z e d e e ?b a a1 e1 d1
426 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 36.3 64a 2 3 25 orch a rd p a rkw a y s a n jo s e, ca 951 3 1 title drawing no. r rev. 64a, 64-le a d, 14 x 14mm body size, 1.0mm body thickne ss , 0.8mm le a d pitch, thin profile pl as tic q ua d fl a t p a ck a ge (tqfp) c 64a 2010-10-20 pin 1 identifier 0~7 pin 1 l c a1 a2 a d1 d e e1 e b common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note note s : 1.thi s p a ck a ge conform s to jedec reference ms-026, v a ri a tion aeb. 2. dimen s ion s d1 a nd e1 do not incl u de mold protr us ion. allow ab le protr us ion i s 0.25mm per s ide. dimen s ion s d1 a nd e1 a re m a xim u m pl as tic b ody s ize dimen s ion s incl u ding mold mi s m a tch. 3 . le a d copl a n a rity i s 0.10mm m a xim u m. a ? ? 1.20 a1 0.05 ? 0.15 a2 0.95 1.00 1.05 d 15.75 16.00 16.25 d1 1 3 .90 14.00 14.10 note 2 e 15.75 16.00 16.25 e1 1 3 .90 14.00 14.10 note 2 b 0. 3 0 ? 0.45 c 0.09 ? 0.20 l 0.45 ? 0.75 e 0.80 typ
427 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 36.4 64m2 2 3 25 orch a rd p a rkw a y s a n jo s e, ca 951 3 1 title drawing no. r rev. 64m2 , 64-p a d, 9 x 9 x 1.0mm bod y, le a d pitch 0.50mm , e 64m2 2010-10-20 common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note a 0.80 0.90 1.00 a1 ? 0.02 0.05 b 0.18 0.25 0. 3 0 d d2 7.50 7.65 7.80 8.90 9.00 9.10 8.90 9.00 9.10 e e2 7.50 7.65 7.80 e 0.50 bsc l0. 3 5 0.40 0.45 top view s ide view bottom view d e m a rked pin# 1 i d seating plane a1 c a c 0.08 1 2 3 k 0.20 0.27 0.40 2. dimen s ion a nd toler a nce conform to asmey14.5m-1994. 0.20 ref a 3 a 3 e2 d2 b e pin #1 corner l pin #1 tr i a ngle pin #1 ch a mfer (c 0. 3 0) option a option b pin #1 notch (0.20 r) option c k k note s : 1. jedec st a nd a rd mo-220, (saw sing u l a tion) fig . 1, vmmd. 7.65mm expo s ed p a d, micro le a d fr a me p a ck a ge (mlf)
428 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 37. errata 37.1 atmega640 rev. b ? inaccurate adc conversion in differential mode with 200 gain ? high current consumption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb. problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.2 atmega640 rev. a ? inaccurate adc conversion in differential mode with 200 gain ? high current consumption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb. problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.3 atmega1280 rev. b ? inaccurate adc conversion in differential mode with 200 gain ? high current consum ption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb.
429 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.4 atmega1280 rev. a ? inaccurate adc conversion in differential mode with 200 gain ? high current consum ption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb. problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.5 atmega1281 rev. b ? inaccurate adc conversion in differential mode with 200 gain ? high current consum ption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb. problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled.
430 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 37.6 atmega1281 rev. a ? inaccurate adc conversion in differential mode with 200 gain ? high current consum ption in sleep mode 1. inaccurate adc conversion in differential mode with 200 gain w ith avcc <3.6v, random conversions will be in accurate. typical absolute accuracy may reach 64 lsb. problem fix/workaround n one. 2. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.7 atmega2560 rev. f n ot sampled. 37.8 atmega2560 rev. e n o known errata. 37.9 atmega2560 rev. d n ot sampled. 37.10 atmega2560 rev. c ? high current consumption in sleep mode 1. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.11 atmega2560 rev. b n ot sampled.
431 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 37.12 atmega2560 rev. a ? non-read-while-write area of flash not functional ? part does not work under 2.4 volts ? incorrect adc reading in differential mode ? internal adc reference has too low value ? in/out instructions may be executed twice when stack is in external ram ? eeprom read from appli cation code does not work in lock bit mode 3 1. non-read-while-write area of flash not functional the n on-read- w hile- w rite area of the flash is not working as expected. the problem is related to the speed of the part when reading the flash of this area. problem fix/workaround - only use the first 248k of the flash. - if boot functionality is needed, run the code in the n on-read- w hile- w rite area at maximum 1/4th of the maximum frequency of the device at any given voltage. this is done by writing the clkpr register before entering the boot section of the code. 2. part does not work under 2.4 volts the part does not execute code correctly below 2.4 volts. problem fix/workaround do not use the part at voltages below 2.4 volts. 3. incorrect adc reading in differential mode the adc has high noise in differential mode. it can give up to 7 lsb error. problem fix/workaround use only the 7 msb of the result when using the adc in differential mode. 4. internal adc reference has too low value the internal adc reference has a value lower than specified. problem fix/workaround - use avcc or external reference. - the actual value of the reference can be measured by applying a known voltage to the adc when using the internal reference. the result when doing later conversions can then be calibrated. 5. in/out instructions may be executed twice when stack is in external ram if either an i n or an out instruction is executed directly before an interrupt occurs and the stack pointer is located in exte rnal ram, the instruction will be ex ecuted twice. in some cases this will cause a prob lem, for example: - if reading sreg it will appear that the i-flag is cleared. - if writing to the pi n registers, the po rt will toggle twice. - if reading registers with interrupt flags, the flags will appea r to be cleared.
432 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 problem fix/workaround there are two application work-arounds, where selecting one of them, will be omitting the issue: - replace i n and out with ld/lds/ldd and st/sts/std instructions. - use internal ram for stack pointer. 6. eeprom read from applic ation code does not work in lock bit mode 3 w hen the memory lock bits lb2 and lb1 are programmed to mode 3, eeprom read does not work from the application code. problem fix/workaround do not set lock bit protection mode 3 when the application code needs to read from eeprom. 37.13 atmega2561 rev. f n ot sampled. 37.14 atmega2561 rev. e n o known errata. 37.15 atmega2561 rev. d n ot sampled. 37.16 atmega2561 rev. c ? high current consumpt ion in sleep mode. 1. high current consumption in sleep mode if a pending interrupt cannot wake the part up from the selected sleep mode, the current consumption will increase during sleep when exec uting the sleep instruction directly after a sei instruction. problem fix/workaround before entering sleep, interrupts not used to wake the part from the sleep mode should be disabled. 37.17 atmega2561 rev. b n ot sampled. 37.18 atmega2561 rev. a ? non-read-while-write area of flash not functional ? part does not work under 2.4 volts ? incorrect adc reading in differential mode ? internal adc reference has too low value ? in/out instructions may be executed twice when stack is in external ram ? eeprom read from applicat ion code does not work in lock bit mode 3
433 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 1. non-read-while-write area of flash not functional the n on-read- w hile- w rite area of the flash is not working as expected. the problem is related to the speed of the part when reading the flash of this area. problem fix/workaround - only use the first 248k of the flash. - if boot functionality is needed, run the code in the n on-read- w hile- w rite area at maximum 1/4th of the maximum frequency of the device at any given voltage. this is done by writing the clkpr register before entering the boot section of the code. 2. part does not work under 2.4 volts the part does not execute code correctly below 2.4 volts. problem fix/workaround do not use the part at voltages below 2.4 volts. 3. incorrect adc reading in differential mode the adc has high noise in differential mode. it can give up to 7 lsb error. problem fix/workaround use only the 7 msb of the result when using the adc in differential mode. 4. internal adc reference has too low value the internal adc reference has a value lower than specified. problem fix/workaround - use avcc or external reference. - the actual value of the reference can be measured by applying a known voltage to the adc when using the internal reference. the result when doing later conversions can then be calibrated. 5. in/out instructions may be executed twice when stack is in external ram if either an i n or an out instruction is executed directly before an interrupt occurs and the stack pointer is located in exte rnal ram, the instruction will be ex ecuted twice. in some cases this will cause a prob lem, for example: - if reading sreg it will appear that the i-flag is cleared. - if writing to the pi n registers, the po rt will toggle twice. - if reading registers with interrupt flags, the flags will appea r to be cleared. problem fix/workaround there are two application workarounds, wher e selecting one of them, will be omitting the issue: - replace i n and out with ld/lds/ldd and st/sts/std instructions. - use internal ram for stack pointer. 6. eeprom read from applic ation code does not work in lock bit mode 3 w hen the memory lock bits lb2 and lb1 are programmed to mode 3, eeprom read does not work from the application code.
434 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 problem fix/workaround do not set lock bit protection mode 3 when the application code needs to read from eeprom.
435 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 38. datasheet revision history please note that the referring page numbers in this section are referring to this document.the referring revision in this section are referring to the document revision. 38.1 rev. 2549p-10/2012 38.2 rev. 2549o-05/12 38.3 rev. 2549n-05/11 38.4 rev. 2549m-09/10 1. replaced drawing in 36.4 ?64m2? on page 427 . 2. former page 439 has been deleted as the content of this page did not belong there (same page as the last page). 3. some small correction made in the setup. 1. the datasheet changed status from preliminary to complete. removed ?preliminary? from the front page. 2. replaced figure 10-3 on page 46 by a new one. 3. updated the last page to include the new address for atmel japan site. 1. added atmel qtouch library support and qtouch sensing capablity features 2. updated cross-reference in ?bit 5, 2:0 - w dp3:0: w atchdog timer prescaler 3, 2, 1 and 0? on page 68 3. updated assembly codes in section ?usart initialization? on page 210 4. added ?standard power-on reset? on page 372 . 5. added ?enhanced power-on reset? on page 373 . 6. updated figure 32-13 on page 393 7. updated ?ordering information? on page 419 to include tape & reel devices. 1. updated typos in figure 26-9 on page 285 and in figure 26-10 on page 285 . 2. n ote is added below table 1-1 on page 3 . 3. the values for ?typical characteristics? in table 31-9 on page 377 and table 31-10 on page 378 , has been rounded. 4. units for t rst and t bod in table 31-3 on page 372 have been changed from ?ns? to ?s?. 5. the figure text for table 31-2 on page 371 has been changed. 6. text in first column in table 30-3 on page 336 has been changed from ?fuse low byte? to ?extended fuse byte?. 7. the text in ?power reduction register? on page 54 has been changed. 8. the value of the inductor in figure 26-9 on page 285 and figure 26-10 on page 285 has been changed to 10h. 9. ?port a? has been changed into ?port k? in the first paragraph of ?features? on page 275 .
436 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 38.5 rev. 2549l-08/07 38.6 rev. 2549k-01/07 38.7 rev. 2549j-09/06 10. minimum wait delay for t w d_eeprom in table 30-16 on page 351 has been changed from 9.0ms to 3.6ms 11. dimension a3 is added in ?64m2? on page 427 . 12. several cross-references are corrected. 13. ?com0a1:0? on page 130 is corrected to ?com0b1:0?. 14. corrected some figure and table numbering. 15. updated section 10.6 ?low frequency cr ystal oscillator? on page 45 . 1. updated note in table 10-11 on page 47 . 2. updated table 10-3 on page 43 , table 10-5 on page 44 , table 10-9 on page 47 . 3. updated typos in ?dc characteristics? on page 367 4. updated ?clock characteristics? on page 371 5. updated ?external clock drive? on page 371 . 6. added ?system and reset characteristics? on page 372 . 7. updated ?spi timing characteristics? on page 375 . 8. updated ?adc characteristics ? preliminary data? on page 377 . 9. updated ordering code in ?atmega640? on page 419 . 1. updated table 1-1 on page 3 . 2. updated ?pin descriptions? on page 7 . 3. updated ?stack pointer? on page 16 . 4. updated ?bit 1 ? eepe: eeprom programming enable? on page 36 . 5. updated assembly code example in ?thus, when the bod is not enabled, after setting the acbg bit or enabling the adc, the user must always allow the refer ence to start up before the output from the analog comparator or adc is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode.? on page 63 . 6: updated ?eimsk ? external interrupt mask register? on page 115 . 7. updated bit description in ?pcifr ? pin change interrupt flag register? on page 116 . 8. updated code example in ?usart initialization? on page 210 . 9. updated figure 26-8 on page 284 . 10. updated ?dc characteristics? on page 367 . 1. updated ?? on page 46 . 2. updated code example in ?moving interrupts between applicat ion and boot section? on page 109 . 3. updated ?timer/counter prescaler? on page 186 . 4. updated ?device identification register? on page 303 . 5. updated ?signature bytes? on page 338 . 6. updated ?instruction set summary? on page 416 .
437 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 38.8 rev. 2549i-07/06 38.9 rev. 2549h-06/06 38.10 rev. 2549g-06/06 38.11 rev. 2549f-04/06 38.12 rev. 2549e-04/06 1. added ?data retention? on page 11 . 2. updated table 16-3 on page 129 , table 16-6 on page 130 , table 16-8 on page 131 , table 17-2 on page 148 , table 17-4 on page 159 , table 17-5 on page 160 , table 20-3 on page 187 , table 20-6 on page 188 and table 20-8 on page 189 . 3. updated ?fast p w m mode? on page 150 . 1. updated ?? on page 46 . 2. updated ?osccal ? oscillator calibration register? on page 50 . 3. added table 31-1 on page 371 . 1. updated ?features? on page 1 . 2. added figure 1-2 on page 3 , table 1-1 on page 3 . 3. updated ?? on page 46 . 4. updated ?power management and sleep modes? on page 52 . 5. updated note for table 12-1 on page 68 . 6. updated figure 26-9 on page 285 and figure 26-10 on page 285 . 7. updated ?setting the boot loader lock bits by spm? on page 324 . 8. updated ?ordering information? on page 419 . 9. added package information ?100c1? on page 425 . 10. updated ?errata? on page 428 . 1. updated figure 9-3 on page 31 , figure 9-4 on page 31 and figure 9-5 on page 32 . 2. updated table 20-2 on page 187 and table 20-3 on page 187 . 3. updated features in ?adc ? analog to digital converter? on page 275 . 4. updated ?fuse bits? on page 336 . 1. updated ?features? on page 1 . 2. updated table 12-1 on page 62 . 3. updated note for table 12-1 on page 62 . 4. updated ?bit 6 ? acbg: analog comparator bandgap select? on page 273 . 5. updated ?prescaling and conversion timing? on page 278 . 5. updated ?maximum speed vs. v cc ? on page 373 . 6. updated ?ordering information? on page 419 .
438 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 38.13 rev. 2549d-12/05 38.14 rev. 2549c-09/05 38.15 rev. 2549b-05/05 38.16 rev. 2549a-03/05 1. advanced information status changed to preliminary. 2. changed number of i/o ports from 51 to 54. 3. updatet typos in ?tccr0a ? timer/counter cont rol register a? on page 129 . 4. updated features in ?adc ? analog to digital converter? on page 275 . 5. updated operation in ?adc ? analog to digital converter? on page 275 6. updated stabilizing time in ?changing channel or reference selection? on page 282 . 7. updated figure 26-1 on page 276 , figure 26-9 on page 285 , figure 26-10 on page 285 . 8. updated text in ?adcsrb ? adc control and status register b? on page 290 . 9. updated n ote for table 4 on page 43 , table 13-15 on page 86 , table 26-3 on page 289 and table 26-6 on page 295 . 10. updated table 31-9 on page 377 and table 31-10 on page 378 . 11. updated ?filling the temporary buffer (page loading)? on page 323 . 12. updated ?typical characteristics? on page 385 . 13. updated ?packaging information? on page 424 . 14. updated ?errata? on page 428 . 1. updated speed grade in section ?features? on page 1 . 2. added ?resources? on page 11 . 3. updated ?spi ? serial peripheral interface? on page 195 . in slave mode, low and high period spi clock must be larger than 2 cpu cycles. 4. updated ?bit rate generator unit? on page 247 . 5. updated ?maximum speed vs. v cc ? on page 373 . 6. updated ?ordering information? on page 419 . 7. updated ?packaging information? on page 424 . package 64m1 replaced by 64m2. 8. updated ?errata? on page 428 . 1. jtag id/signature for atmega640 updated: 0x9608. 2. updated table 13-7 on page 81 . 3. updated ?serial programming instruction set? on page 352 . 4. updated ?errata? on page 428 . 1. initial version.
i 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 table of contents features ................ ................ .............. ............... .............. .............. ............ 1 1 pin configurations ..... ................ ................. ................ ................. ............ 2 2 overview ............ ................ ................ ............... .............. .............. ............ 5 2.1 block diagram ...................................................................................................5 2.2 comparison between atmega1281/2561 and atmega640/1280/2560 ...........7 2.3 pin descriptions .................................................................................................7 3 resources .............. .............. .............. ............... .............. .............. .......... 11 4 about code examples ........ .............. ............... .............. .............. .......... 11 5 data retention .......... ................ ................ ................. ................ ............. 11 6 capacitive touch sensing ................. ............... .............. .............. .......... 11 7 avr cpu core ................. ................ ................. .............. .............. .......... 12 7.1 introduction ......................................................................................................12 7.2 architectural overview .....................................................................................12 7.3 alu ? arithmetic logic unit .............................................................................13 7.4 status register ................................................................................................14 7.5 general purpose register file ........................................................................15 7.6 stack pointer ...................................................................................................16 7.7 instruction execution timing ...........................................................................17 7.8 reset and interrupt handling ...........................................................................18 8 avr memories .......... ................ ................ ................. ................ ............. 21 8.1 in-system reprogrammable flash program memory .....................................21 8.2 sram data memory ........................................................................................21 8.3 eeprom data memory . ................. ................ ............. ............ ............. ..........23 8.4 i/o memory ......................................................................................................27 9 external memory interface . .............. ............... .............. .............. .......... 28 9.1 overview ..........................................................................................................28 9.2 register description ........................................................................................35 9.3 general purpose registers ...............................................................................37 9.4 external memory registers ...............................................................................37 10 system clock and clock options .............. ................ ................. .......... 40 10.1 overview ..........................................................................................................40
ii 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 10.2 clock systems and their distribution ...............................................................40 10.3 clock sources .................................................................................................41 10.4 low power crystal oscillator ...........................................................................42 10.5 full swing crystal oscillator ............... .............................................................44 10.6 low frequency crystal oscillator ....................................................................45 10.7 calibrated internal rc oscillator .....................................................................47 10.8 128 khz internal oscillator ..............................................................................47 10.9 external clock .................................................................................................48 10.10 clock output buffer .........................................................................................49 10.11 timer/counter oscillator ..................................................................................49 10.12 system clock prescaler ..................................................................................49 10.13 register description ........................................................................................50 11 power management and sleep modes ........ ................. .............. .......... 52 11.1 sleep modes ....................................................................................................52 11.2 idle mode .........................................................................................................52 11.3 adc n oise reduction mode ............................................................................53 11.4 power-down mode ...........................................................................................53 11.5 power-save mode ............................................................................................53 11.6 standby mode .................................................................................................54 11.7 extended standby mode .................................................................................54 11.8 power reduction register ...............................................................................54 11.9 minimizing power consumption ......................................................................54 11.10 register description ........................................................................................56 12 system control and reset .... .............. .............. .............. .............. ........ 59 12.1 resetting the avr ...........................................................................................59 12.2 reset sources .................................................................................................59 12.3 internal voltage reference ..............................................................................62 12.4 w atchdog timer ..............................................................................................63 12.5 register description ........................................................................................67 13 i/o-ports ........ ................ ................. ................ ................. .............. .......... 70 13.1 introduction ......................................................................................................70 13.2 ports as general digital i/o .............................................................................71 13.3 alternate port functions ..................................................................................75 13.4 register description for i/o-ports ..................................................................100 14 interrupts ............. .............. .............. .............. .............. .............. ........... 105
iii 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 14.1 interrupt vectors in atmega640/1280/1281/2560/2561 ................................105 14.2 reset and interrupt vector placement ...........................................................107 14.3 moving interrupts between application and boot section .............................109 14.4 register description ......................................................................................110 15 external interrupts .......... ................ .............. .............. .............. ........... 112 15.1 pin change interrupt timing ..........................................................................112 15.2 register description ......................................................................................113 16 8-bit timer/counter0 with pwm ................... .............. .............. ........... 118 16.1 features ........................................................................................................118 16.2 overview ........................................................................................................118 16.3 timer/counter clock sources .......................................................................119 16.4 counter unit ..................................................................................................119 16.5 output compare unit .....................................................................................120 16.6 compare match output unit ..........................................................................122 16.7 modes of operation .......................................................................................123 16.8 timer/counter timing diagrams ...................................................................127 16.9 register description ......................................................................................129 17 16-bit timer/counter (timer /counter 1, 3, 4, and 5) ............... ........... 136 17.1 features ........................................................................................................136 17.2 overview ........................................................................................................136 17.3 accessing 16-bit registers ............................................................................138 17.4 timer/counter clock sources .......................................................................141 17.5 counter unit ..................................................................................................142 17.6 input capture unit .........................................................................................143 17.7 output compare units ...................................................................................145 17.8 compare match output unit ..........................................................................147 17.9 modes of operation .......................................................................................148 17.10 timer/counter timing diagrams ...................................................................156 17.11 register description ......................................................................................158 18 timer/counter 0, 1, 3, 4, and 5 prescaler ........... ............ ............ ........ 169 18.1 internal clock source ....................................................................................169 18.2 prescaler reset .............................................................................................169 18.3 external clock source ...................................................................................169 18.4 register description ......................................................................................170
iv 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 19 output compare modulato r (ocm1c0a) ....... .............. .............. ........ 172 19.1 overview ........................................................................................................172 19.2 description .....................................................................................................172 20 8-bit timer/counter2 with pw m and asynchronous operation ...... 174 20.1 overview ........................................................................................................174 20.2 timer/counter clock sources .......................................................................175 20.3 counter unit ..................................................................................................175 20.4 modes of operation .......................................................................................176 20.5 output compare unit .....................................................................................180 20.6 compare match output unit ..........................................................................182 20.7 timer/counter timing diagrams ...................................................................183 20.8 asynchronous operation of timer/counter2 .................................................184 20.9 timer/counter prescaler ...............................................................................186 20.10 register description ......................................................................................187 21 spi ? serial peripheral interface ......... .............. .............. ............ ........ 195 21.1 ss pin functionality ......................................................................................200 21.2 register description ......................................................................................202 22 usart ............. ................. ................ .............. .............. .............. ........... 205 22.1 features ........................................................................................................205 22.2 clock generation ...........................................................................................206 22.3 frame formats ..............................................................................................209 22.4 usart initialization .......................................................................................210 22.5 data transmission ? the usart transmitter ..............................................212 22.6 data reception ? the usart receiver .......................................................214 22.7 asynchronous data reception ......................................................................218 22.8 multi-processor communication mode ..........................................................221 22.9 register description ......................................................................................222 22.10 examples of baud rate setting .....................................................................227 23 usart in spi mode .......... .............. .............. .............. .............. ........... 232 23.1 overview ........................................................................................................232 23.2 usart mspim vs. spi .................................................................................232 23.3 spi data modes and timing ..........................................................................233 23.4 frame formats ..............................................................................................234 23.5 data transfer .................................................................................................236 23.6 usart mspim register description ............................................................237
v 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 24 2-wire serial interface ..... ................ .............. .............. .............. ........... 241 24.1 features ........................................................................................................241 24.2 2-wire serial interface bus definition ............................................................241 24.3 data transfer and frame format ..................................................................242 24.4 multi-master bus systems, arbitration and synchronization .........................245 24.5 overview of the t w i module .........................................................................246 24.6 using the t w i ................................................................................................249 24.7 transmission modes .....................................................................................252 24.8 multi-master systems and arbitration ............................................................265 24.9 register description ......................................................................................266 25 ac ? analog comparator ... .............. ............... .............. .............. ........ 271 25.1 analog comparator multiplexed input ...........................................................271 25.2 register description ......................................................................................272 26 adc ? analog to digital co nverter .............. .............. .............. ........... 275 26.1 features ........................................................................................................275 26.2 operation .......................................................................................................276 26.3 starting a conversion ....................................................................................277 26.4 prescaling and conversion timing ................................................................278 26.5 changing channel or reference selection ...................................................282 26.6 adc n oise canceler .....................................................................................283 26.7 adc conversion result .................................................................................288 26.8 register description ......................................................................................289 27 jtag interface and on-chi p debug system ............ .............. ........... 296 27.1 features ........................................................................................................296 27.2 overview ........................................................................................................296 27.3 tap - test access port .................................................................................297 27.4 using the boundary-scan chain ....................................................................299 27.5 using the on-chip debug system .................................................................299 27.6 on-chip debug specific jtag instructions ...................................................300 27.7 using the jtag programming capabilitie s ...................................................301 27.8 bibliography ...................................................................................................301 27.9 on-chip debug related register in i/o memory ...........................................301 28 ieee 1149.1 (jtag) boundary-scan ....... ................. ................ ........... 302 28.1 features ........................................................................................................302 28.2 system overview ...........................................................................................302
vi 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 28.3 data registers ...............................................................................................302 28.4 boundary-scan specific jtag instructions ...................................................304 28.5 boundary-scan chain ....................................................................................305 28.6 boundary-scan related register in i/o memory ...........................................308 28.7 atmega640/1280/1281/2560/2561 boundary-scan order ............................308 28.8 boundary-scan description language files ..................................................308 29 boot loader support ? read-while-wri te self-programming ......... 317 29.1 features ........................................................................................................317 29.2 application and boot loader flash sections .................................................317 29.3 read- w hile- w rite and n o read- w hile- w rite flash sections ........................317 29.4 boot loader lock bits ...................................................................................320 29.5 addressing the flash during self-programming ...........................................322 29.6 self-programming the flash ..........................................................................323 29.7 register description ......................................................................................332 30 memory programming ........ .............. ............... .............. .............. ........ 335 30.1 program and data memory lock bits ...........................................................335 30.2 fuse bits ........................................................................................................336 30.3 signature bytes .............................................................................................338 30.4 calibration byte .............................................................................................338 30.5 page size ......................................................................................................338 30.6 parallel programming parameters, pin mapping, and commands ...............338 30.7 parallel programming ....................................................................................341 30.8 serial downloading ........................................................................................349 30.9 programming via the jtag interface ............................................................354 31 electrical characteristics ... .............. ............... .............. .............. ........ 367 31.1 dc characteristics .........................................................................................367 31.2 speed grades ...............................................................................................369 31.3 clock characteristics .....................................................................................371 31.4 external clock drive ......................................................................................371 31.5 system and reset characteristics ................................................................372 31.6 2-wire serial interface characteristics ...........................................................373 31.7 spi timing characteristics ............................................................................375 31.8 adc characteristics ? preliminary data ........................................................377 31.9 external data memory timing .......................................................................379 32 typical characteristics ....... .............. ............... .............. .............. ........ 385
vii 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 32.1 active supply current ....................................................................................385 32.2 idle supply current ........................................................................................388 32.3 power-down supply current ..........................................................................392 32.4 power-save supply current ...........................................................................393 32.5 standby supply current ................................................................................394 32.6 pin pull-up .....................................................................................................394 32.7 pin driver strength ........................................................................................397 32.8 pin threshold and hysteresis ........................................................................399 32.9 bod threshold and analog comparator offset ............................................402 32.10 internal oscillator speed ...............................................................................404 32.11 current consumption of peripheral units ......................................................406 32.12 current consumption in reset and reset pulsewidth ..................................409 33 register summary ............ .............. .............. .............. .............. ........... 411 34 instruction set summary ... .............. ............... .............. .............. ........ 416 35 ordering information .......... .............. ............... .............. .............. ........ 419 35.1 atmega640 ...................................................................................................419 35.2 atmega1280 .................................................................................................420 35.3 atmega1281 .................................................................................................421 35.4 atmega2560 .................................................................................................422 35.5 atmega2561 .................................................................................................423 36 packaging information .......... ................ ................. ................ ............. 424 36.1 100a ..............................................................................................................424 36.2 100c1 ............................................................................................................425 36.3 64a ................................................................................................................426 36.4 64m2 ..............................................................................................................427 37 errata ........... ................ ................ ................. ................ .............. ........... 428 37.1 atmega640 rev. b .........................................................................................428 37.2 atmega640 rev. a .........................................................................................428 37.3 atmega1280 rev. b .......................................................................................428 37.4 atmega1280 rev. a .......................................................................................429 37.5 atmega1281 rev. b .......................................................................................429 37.6 atmega1281 rev. a .......................................................................................430 37.7 atmega2560 rev. f .......................................................................................430 37.8 atmega2560 rev. e .......................................................................................430
viii 2549p?avr?10/2012 atmega640/1280/1281/2560/2561 37.9 atmega2560 rev. d ......................................................................................430 37.10 atmega2560 rev. c ......................................................................................430 37.11 atmega2560 rev. b .......................................................................................430 37.12 atmega2560 rev. a .......................................................................................431 37.13 atmega2561 rev. f .......................................................................................432 37.14 atmega2561 rev. e .......................................................................................432 37.15 atmega2561 rev. d ......................................................................................432 37.16 atmega2561 rev. c ......................................................................................432 37.17 atmega2561 rev. b .......................................................................................432 37.18 atmega2561 rev. a .......................................................................................432 38 datasheet revision history .. ................ ................. ................ ............. 435 38.1 rev. 2549p-10/2012 ......................................................................................435 38.2 rev. 2549o-05/12 .........................................................................................435 38.3 rev. 2549 n -05/11 .........................................................................................435 38.4 rev. 2549m-09/10 .........................................................................................435 38.5 rev. 2549l-08/07 ..........................................................................................436 38.6 rev. 2549k-01/07 ..........................................................................................436 38.7 rev. 2549j-09/06 ..........................................................................................436 38.8 rev. 2549i-07/06 ...........................................................................................437 38.9 rev. 2549h-06/06 .........................................................................................437 38.10 rev. 2549g-06/06 .........................................................................................437 38.11 rev. 2549f-04/06 ..........................................................................................437 38.12 rev. 2549e-04/06 ..........................................................................................437 38.13 rev. 2549d-12/05 .........................................................................................438 38.14 rev. 2549c-09/05 .........................................................................................438 38.15 rev. 2549b-05/05 ..........................................................................................438 38.16 rev. 2549a-03/05 ..........................................................................................438 table of contents.......... ................. ................ ................. ................ ........... i
2549p?avr?10/2012 atmel corporation 2325 orchard parkway san jose, ca 95131 usa tel : (+1)(408) 441-0311 fax : (+1)(408) 487-2600 www.atmel.com atmel asia limited unit 1-5 & 16, 19/f bea tower, millennium city 5 418 kwun tong road kwun tong, kowloon ho n g ko n g tel : (+852) 2245-6100 fax : (+852) 2722-1369 atmel munich gmbh business campus parkring 4 d-85748 garching b. munich germa n y tel : (+49) 89-31970-0 fax : (+49) 89-3194621 atmel japan 16f, shin-osaki kangyo bldg. 1-6-8 osaki shinagawa-ku tokyo 141-0032 japa n tel : (+81)(3) 6417-0300 fax : (+81)(3) 6417-0370 ? 2012 atmel corporation. all rights reserved. atmel ? , atmel logo and combinations thereof, avr ? , qtouch ? , qmatrix ? , avr studio ? and others are registered trademarks or trade- marks of atmel corporation or its subsidiaries. w indows ? and others are registered trademarks of microsoft corporation in u.s. and other countries. other terms and product names may be trademarks of others. disclaimer: the information in this document is provided in connection with atmel products. n o license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in the atmel terms and conditions of sales located on the atmel website, atmel assumes no liability whatsoever and disclaims any express, implied or statutory warranty relating to its pro ducts including, but not limited to, the implied warranty of merchantability, fitness for a particular purp ose, or non-infringement. in no even t shall atmel be liable for any direct, indirect, consequential, punitive, special or incidental damages (including, without limitati on, damages for loss and prof- its, business interruption, or loss of information) arising out of the use or inability to use this document, even if atmel has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or com- pleteness of the contents of th is document and reserves the right to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information cont ained herein. unless specifically provided otherwise, atmel pr oducts are not suit- able for, and shall not be used in, automotive applications. atme l products are not intended, authorized, or warranted for use as components in applica- tions intended to support or sustain life.


▲Up To Search▲   

 
Price & Availability of ATTINY84V-10MUR

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X